stack 常用接口
功能描述:栈容器常用的对外接口
构造函数:
stack<T> stk;
//stack采用模板类实现, stack对象的默认构造形式stack(const stack &stk);
//拷贝构造函数
赋值操作:
stack& operator=(const stack &stk);
//重载等号操作符
数据存取:
push(elem);
//向栈顶添加元素pop();
//从栈顶移除第一个元素top();
//返回栈顶元素
大小操作:
empty();
//判断堆栈是否为空size();
//返回栈的大小
#include <iostream>
#include <stack>
using namespace std;
void test()
{
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
cout << "size of the stack is: " << s.size() << endl;
while(!s.empty()){
cout << "top element of stack is " << s.top() << endl;
s.pop();
}
cout << "size of the stack is: " << s.size() << endl;
}
int main(){
test();
return 0;
}
queue 常用接口
功能描述:栈容器常用的对外接口
构造函数:
queue<T> que;
//queue采用模板类实现,queue对象的默认构造形式queue(const queue &que);
//拷贝构造函数
赋值操作:
queue& operator=(const queue &que);
//重载等号操作符
数据存取:
push(elem);
//往队尾添加元素pop();
//从队头移除第一个元素back();
//返回最后一个元素front();
//返回第一个元素
大小操作:
empty();
//判断堆栈是否为空size();
//返回栈的大小
#include <string>
#include <iostream>
#include <queue>
using namespace std;
class Person
{
public:
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void test()
{
queue<Person> q;
Person p1("Alice", 30);
Person p2("Bob", 40);
Person p3("Cace", 50);
Person p4("David", 60);
q.push(p1);
q.push(p2);
q.push(p3);
q.push(p4);
while(!q.empty()){
cout << "top of queue: " << endl << "name: " << q.front().m_name << endl
<< "age: " << q.front().m_age << endl;
cout << "end of queue: " << endl << "name: " << q.back().m_name << endl
<< "age: " << q.back().m_age << endl;
cout << endl;
q.pop();
}
cout << "size of queue is: " << q.size() << endl;
}
int main(){
test();
return 0;
}