這倆容器較爲簡單,都不可遍歷容器。
stack只能訪問棧頂元素。 stack--棧
queue只能訪問隊列中首尾元素。 queue--隊列
void test01()
{
stack <int> s;
//入棧
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
while (s.empty() == 0) //等於1代表空
{
//僅能使用s.top查看棧頂元素
cout << "棧頂元素爲 " << s.top() << endl;
s.pop();
}
cout << "棧的大小爲: "<<s.size() << endl;
}
void test02()
{
queue <int >q;
//入隊
q.push(10);
q.push(20);
q.push(30);
q.push(40);
q.push(50);
while (q.empty() == 0) //只要隊列不爲空
{
//僅能訪問隊首和隊尾
cout << "隊頭元素" << q.front() <<" ";
cout << "隊尾元素" << q.back() << endl;
cout << endl;
q.pop();//出列
}
cout << "隊列的大小爲" << q.size()<<endl;
}