之前学数据结构时自己写过stack和queue这两个最经典的数据结构,但是在真正写代码时不可能真的调用自己所写的头文件。一是因为要把写好的头文件cv到每个project中,二是clion中直接有这些经典数据结构的头文件并且效率很高,直接引用即可。
Stack
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> s;
s.push(1);
s.push(2);
int a = s.top();
s.pop();
int b = s.top();
cout << a << " " << b << endl;
}
从代码中可以了解到stack的一些基础知识和操作。
stack是一个模版类,使用时需要加上存储元素的类型。
push压栈
pop出栈
top取得栈顶元素
size大小
empty判空
emplace基本等同于push,如果入栈的参数是结构体或类,emplace可以直接调用其构造函数。
class A
{
A(int,int);
};
int main()
{
stack<A> s;
s.emplace(1,2);
}
swap交换两个栈中的元素
stack<int> a;
stack<int> b;
a.swap(b); //交换a b两个栈的元素 or b.swap(a)
支持=copy一个stack
Queue
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
cout << q.front() << " " << q.back() << endl;
q.pop();
cout << q.front() << " " << q.back() << endl;
}
//输出:
//1 3
//2 3
和stack一样也是模版类
push
pop
front队首元素
back队尾元素
size
empty
emplace
swap
没写的操作均与stack相同