stackは先入れあと出し(LIFO、last-in first-out)のスタックとして機能するコンテナアダプタです。
stackはアダプタなので、データを保存するために連接コンテナ(vector、list、deque)のいずれかを使います。
stackは次のように定義されています。
namespace std {
template <typename T, typename Container = deque<T> >
class stack {
};
}
次の例は、vectorコンテナを使ったstackに整数を保存する例です。
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
stack< int , vector< int > > stk;
stk.push(1);
stk.push(2);
stk.push(3);
stk.push(4);
stk.push(5);
while (!stk.empty())
{
cout << stk.top() << " ";
stk.pop();
}
cout << endl;
return 0;
}
実行結果は次のようになります。
5 4 3 2 1