您的位置:首页 > 其它

STL学习记录(十五):Stack

2015-07-31 22:33 323 查看

STL中的特殊容器Stack

准确来说Stack是容器适配器类型,与我们数据结构中所学的概念一样这种容器的特性就是Last Input First Output。该容器通过push、

pop方法对栈头的元素进行操作。主要的成员函数如下:

成员函数说明
empty( )判断栈是否为空
size( )返回栈的大小
push( val )将元素加入到栈首
pop( )取出栈中的首元素
top( )访问栈首元素
emplace( val )将元素加入到栈首,元素在作为参数传递的时候通过自身构造函数构造
swap( stc )将stc栈进行元素交换
代码示例:

// stack::swap stack::size
#include <iostream>
#include <stack>
using namespace std;

int main ()
{
stack<int> foo,bar;
foo.push (10); foo.push(20); foo.push(30);
bar.push (111); bar.push(222);

foo.swap(bar);

cout << "size of foo: " << foo.size() << endl;
cout << "size of bar: " << bar.size() << endl;

return 0;
}


// stack::push/pop
#include <iostream>
#include <stack>
using namespace std;

int main ()
{
stack<int> mystack;

for (int i=0; i<5; ++i) mystack.push(i);

cout << "Popping out elements...";
while (!mystack.empty())
{
cout << ' ' << mystack.top();
mystack.pop();
}
cout << endl;

return 0;
}


// stack::emplace
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main ()
{
stack<string> mystack;

mystack.emplace ("First sentence");
mystack.emplace ("Second sentence");

cout << "mystack contains:\n";
while (!mystack.empty())
{
cout << mystack.top() << endl;
mystack.pop();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: