q.push(1); // append from end q.front(); // return q[0] q.size(); // return len(q) q.pop(); // pop from front q.empty(); // return if q is empty (bool)
Stack (LIFO)
1 2 3 4 5 6 7
stack<int> s;
s.push(1); // append from end s.top(); // return s[-1] s.size(); // return len(s) s.pop(); // pop from end s.empty(); // return if s is empty (bool)
Set
對應 Python:類似有序(且會自動排序)的 set
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
set<int> s;
s.insert(2); // add
s.erase(5); // remove value 5 if it exists s.find(2); // return iterator of s (return end() if not in s)
for(auto iter = s.begin(); iter != s.end(); iter++) cout << *iter << '\n'; // print all elements in s
cout << *prev(s.end()) << '\n'; // s[-1] (= max element) // prev(it) / next(it) return nearby iterators without modifying it
auto it = s.upper_bound(x); // find first element that > x // auto it = s.lower_bound(x); // find first element >= x if(it != s.end()) cout << *it << '\n'; // check if such element exists
set:有序、自動排列、不重複
unordered_set:無序、不重複
multiset:有序、自動排列、可重複
unordered_multiset:無序、可重複
Map
對應 Python:有序(且會自動排序)的 dict(且會自動指派值,若 key 從未被定義過)
1 2 3 4 5 6 7 8 9 10 11
map<string, int> m;
m["apple"] = 3; m["banana"]++; // no need exist before this line
m["orange"]; // return value of key (0 if key DNE)
m.erase("orange"); // same as set
for(auto i : m) cout << i.first << ' ' << i.second << '\n'; // print all k and v