スタック
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s;
s.push(0);
s.push(1);
cout << s.top() << endl; //=> 1
cout << s.size() << endl; //=> 2
s.pop();
cout << s.top() << endl; //=> 0
cout << s.size() << endl; //=> 1
s.pop();
cout << boolalpha << s.empty() << endl; //=> true
return 0;
}
キュー
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q;
q.push(0);
q.push(1);
cout << q.front() << endl; //=> 0
cout << q.back() << endl; //=> 1
cout << q.size() << endl; //=> 2
q.pop();
cout << q.front() << endl; //=> 1
cout << q.back() << endl; //=> 1
cout << q.size() << endl; //=> 1
q.pop();
cout << boolalpha << q.empty() << endl; //=> true
return 0;
}
両端キュー
#include <iostream>
#include <deque>
using namespace std;
int main() {
deque<int> dq; // double-ended queue
dq.push_back(0);
dq.push_back(1);
cout << dq.size() << endl; //=> 2
cout << dq.at(0) << endl; //=> 0
cout << dq[1] << endl; //=> 1
cout << dq.front() << endl; //=> 0
cout << dq.back() << endl; //=> 1
dq.push_front(-1);
dq.pop_back();
cout << dq.size() << endl; //=> 2
cout << dq.at(0) << endl; //=> -1
cout << dq[1] << endl; //=> 0
cout << dq.front() << endl; //=> -1
cout << dq.back() << endl; //=> 0
dq.push_back(1);
dq.pop_front();
cout << dq.size() << endl; //=> 2
cout << dq.at(0) << endl; //=> 0
cout << dq[1] << endl; //=> 1
cout << dq.front() << endl; //=> 0
cout << dq.back() << endl; //=> 1
dq.clear();
cout << dq.size() << endl; //=> 0
cout << boolalpha << dq.empty() << endl; //=> true
return 0;
}
優先度つきキュー
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<int> pq; // 既定は降順 (通常の sort 等とは逆)
// priority_queue<int, vector<int>, less<int> > pq; // 明示的な降順
// priority_queue<int, vector<int>, greater<int> > pq; // 昇順
pq.push(3);
pq.push(1);
pq.push(2);
while(! pq.empty()) {
cout << pq.top() << ' ' << flush; //=> 3 2 1
pq.pop();
}
cout << endl;
return 0;
}