【STL】C++ stack(栈) 基本使用

目录

[一 stack常见构造](#一 stack常见构造)

[1 空容器构造函数(默认构造函数)](#1 空容器构造函数(默认构造函数))

[2. 使用指定容器构造](#2. 使用指定容器构造)

[3 拷贝构造函数](#3 拷贝构造函数)

[二 其他操作](#二 其他操作)

[1 empty](#1 empty)

[2 size](#2 size)

[3 top](#3 top)

[4 push && pop](#4 push && pop)

[5 emplace](#5 emplace)

[6 swap](#6 swap)

[三 总结](#三 总结)


一 stack常见构造

1 空容器构造函数(默认构造函数)

构造一个没有元素的空容器。

2. 使用指定容器构造

可以使用指定的底层容器来构造栈,默认是 std::deque,但也可以是 std::vectorstd::list

3 拷贝构造函数

构造一个容器,其中包含 x 中每个元素的副本,顺序相同

cpp 复制代码
#include<stack>
#include<vector>
#include<iostream>
using namespace std;


int main()
{
	stack<int> st1;

	vector<int> v{ 1, 2, 3, 4 };
	stack<int, vector<int>> st2(v);
	cout << " st2: " << st2.size() << endl;


	stack<int, vector<int>> st3(st2);
	cout << " st3: " << st3.size() << endl;

	stack<int> st4(st1);
	cout << " st4: " << st4.size() << endl;

	return 0;

}

二 其他操作

1 empty

返回容器是否为空(即其大小是否为 0)

cpp 复制代码
void Test1()
{
	stack<int> st;
	if (st.empty()) cout << " st is empty" << endl;
	else cout << "st is not empty" << endl;
}

2 size

上面已经演示过了, 这里不说明了

3 top

返回栈顶元素

cpp 复制代码
void Test2()
{
	vector<int> v{ 1, 2, 3, 4 };
	stack<int, vector<int>> st(v);

	cout << st.top() << endl;
}

4 push && pop

cpp 复制代码
void push (const value_type& val);
void push (value_type&& val);
void pop();
cpp 复制代码
void Test3()
{
	
	stack<int> st;
	st.push(1);
	st.push(2);
	st.push(3);

	while (!st.empty())
	{
		cout << st.top() << endl;
		st.pop();
	}

}

5 emplace

emplace 作用和 push 一样的, 只是效率不一样, 涉及到了右值引用问题, 后面再讲

cpp 复制代码
void Test4()
{
	stack<string> st;
	st.emplace("first");
	st.emplace("second");

	while (!st.empty())
	{
		cout << st.top() << endl;
		st.pop();
	}
}

6 swap

交换两个容器的内容

cpp 复制代码
void swap (stack& x)
cpp 复制代码
void Test5()
{
	stack<int> st1, st2;

	st1.push(1);
	st1.push(2);
	cout << st1.size() << endl;

	st2.push(10);
	st2.push(20);
	st2.push(30);
	cout << st2.size() << endl;

	st1.swap(st2);
	cout << st1.size() << endl;
	cout << st2.size() << endl;
}

三 总结

这节栈的使用非常简单的, 感觉没有啥要讲的, 重要的是后面 栈的模拟实现还有和 队列联合使用. 对本节概念不清楚的, 可以看看我之前写的栈数据结构. 那里就很清晰了.

这两天成都一直下雨, 冷. 脑壳还有点晕, 最近学习Linux系统, 学到线程了, 早听说线程难, 没想到这么难.继续加油吧!

相关推荐
blasit2 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_3 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星3 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛5 天前
delete又未完全delete
c++
端平入洛6 天前
auto有时不auto
c++
哇哈哈20216 天前
信号量和信号
linux·c++
多恩Stone6 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马7 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝7 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc7 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法