1、stack——容器适配器之一,实现堆栈功能,及FILO(先进后出)的数据结构,成员函数有push, pop, size, top, empty;
#include <iostream> #include <stack> #include <vector> #include <algorithm> #include <numeric> using namespace std; int main () { vector<int> v1(5), v2(5), v3(5); iota(v1.begin(), v1.end(), 0); iota(v2.begin(), v2.end(), 5); iota(v3.begin(), v3.end(), 10); stack<vector<int> > s; s.push(v1); s.push(v2); s.push(v3); cout << "size of stack 's' = " << s.size() << endl; if ( v3 != v2 ) s.pop(); cout << "size of stack 's' = " << s.size() << endl; vector<int> top = s.top(); cout << "Contents of v2 : "; copy(top.begin(),top.end(), ostream_iterator(cout," ")); cout << endl; while ( !s.empty() ) s.pop(); cout << "Stack 's' is " << (s.empty() ? "" : "not ") << "empty" << endl; return 0; } 运行结果: // size of stack 's' = 3 // size of stack 's' = 2 // Contents of v2 : 5 6 7 8 9 // Stack 's' is empty
2、queue——容器适配器之一,实现队列功能,及FIFO(先进先出)的数据结构,成员函数有push, pop, size, front, back, empty;
#include <iostream> #include <queue> #include <string> using namespace std; int main () { string s1("C++"); string s2("is"); string s3("powerfull"); string s4("language"); queue que; que.push(s1); que.push(s2); que.push(s3); que.push(s4); cout << "size of queue 'que' = " << que.size() << endl; string temp = que.back(); cout << temp << endl; while ( !que.empty() ) { temp = que.front(); cout << temp << " "; que.pop(); } cout << endl; return 0; } 运行结果: // size of queue 'que' = 4 // language // C++ is powerfull language
3、priority_queue——容器适配器之一,实现增强型队列功能,及FIFO(先进先出)的数据结构,可以自定义优先级算法;
#include <iostream> #include <queue> #include <vector> #include <string> using namespace std; int main () { priority_queue<int, vector<int>, less<int> > ipq; ipq.push(100); ipq.push(200); ipq.push(300); cout << "size of priority_queue ipq = " << ipq.size() << endl; cout << "ipq <int,vector<int>, less<int> > = "; while ( !ipq.empty() ) { cout << ipq.top() << " "; ipq.pop(); } cout << endl << endl; cout << "priority_queue<string,vector<string> > spq;" << endl; priority_queue<string,vector<string> > spq; for ( int i=1; i<10; i++ ) spq.push(string(i,'*')); while ( !spq.empty() ) { cout << spq.top() << endl; spq.pop(); } return 0; } 运行结果: // size of priority_queue ipq = 3 // ipq <sring,vector<string> > = 300 200 100 // // priority_queue<string,vector<string> > spq; // ********* // ******** // ******* // ****** // ***** // **** // *** // ** // *
除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。