C++STLのstack
40066 ワード
stackテンプレートクラスの定義はヘッダファイルにあります.
stackテンプレートクラスには、要素タイプとコンテナタイプの2つのテンプレートパラメータが必要ですが、要素タイプのみが必要です.
の場合、コンテナタイプを指定しない場合、デフォルトのコンテナタイプはdequeです.
stackオブジェクトを定義するコードの例は、次のとおりです.
stack s1;
stack s2;
stackの基本的な操作は次のとおりです.
例:s.push(x);
例:s.pop();スタックアウト操作は、スタックトップ要素を削除するだけで、その要素は返されません.
例:s.top()のようなスタックトップへのアクセス
例:s.empty()のようにスタックが空であると判断し、スタックが空であるとtrueを返す.
例:s.size()などのアクセススタック内の要素の数.
stack::empty
空かどうかを判断します.
Return Value
true if the container size is 0, false otherwise.
[cpp] view plain copy
// stack::empty
#include
#include
using namespace std;
int main ()
{
stack mystack;
int sum (0);
for (int i=1;i<=10;i++) mystack.push(i);
while (!mystack.empty())
{
sum += mystack.top();
mystack.pop();
}
cout << "total: " << sum << endl;
return 0;
}
Output:
stack::pop
void pop ( );
スタックの上部から要素を除去します.
stackテンプレートクラスには、要素タイプとコンテナタイプの2つのテンプレートパラメータが必要ですが、要素タイプのみが必要です.
の場合、コンテナタイプを指定しない場合、デフォルトのコンテナタイプはdequeです.
stackオブジェクトを定義するコードの例は、次のとおりです.
stack
stack
stackの基本的な操作は次のとおりです.
例:s.push(x);
例:s.pop();スタックアウト操作は、スタックトップ要素を削除するだけで、その要素は返されません.
例:s.top()のようなスタックトップへのアクセス
例:s.empty()のようにスタックが空であると判断し、スタックが空であるとtrueを返す.
例:s.size()などのアクセススタック内の要素の数.
stack::empty
bool empty ( ) const;
空かどうかを判断します.
Return Value
true if the container size is 0, false otherwise.
[cpp] view plain copy
// stack::empty
#include
#include
using namespace std;
int main ()
{
stack
int sum (0);
for (int i=1;i<=10;i++) mystack.push(i);
while (!mystack.empty())
{
sum += mystack.top();
mystack.pop();
}
cout << "total: " << sum << endl;
return 0;
}
Output:
total: 55
stack::pop
void pop ( );
スタックの上部から要素を除去します.
Output:
Popping out elements... 4 3 2 1 0
stack::push
void push ( const T& x );
Output:
Popping out elements... 4 3 2 1 0
stack::size
size_type size ( ) const;
Output: 0. size: 0
1. size: 5
2. size: 4
stack::top
value_type& top ( );
const value_type& top ( ) const;
スタックトップ を す
[cpp] view plain copy
// test_stack.cpp:コンソールアプリケーションのエントリポイントを します.
//
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
stack mystack;
mystack.push(10);
mystack.push(20);
mystack.top()-=5;
cout << "mystack.top() is now " << mystack.top() << endl;
return 0;
}
Output: mystack.top() is now 15