Vector #include <vector>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 vector<int > a; for (int i=0 ; i<10 ; i++) { a.push_back (i); } a.pop_back (); cout << a.front (); cout << a[0 ]; cout << a.at (index); cout << a[index]; cout << a.back (); cout << a[a.size ()-1 ]; vector<int >::iterator it; for (it=a.begin (); it!=a.end (); it++) { cout << *it << endl; } int size = a.size ();for (int i=0 ; i<size; i++) { cout << a[i] << endl; } vector<int >::iterator it, it2; it = a.begin () + 1 ; it2 = a.begin () + 3 ; a.erase (it); a.erase (it, it2); a.clear (); a.empty (); it = a.begin (); a.insert (it, -1 ); a.insert (it, 2 , -2 ); #include <algorithm> sort (a.begin (), a.end ());a.swap (b);
Stack #include <stack>
默认的容器类型是deque(d ouble e nded que ue 双端队列),让双端队列展示栈的性质。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 stack<int > s; s.push (1 ); s.pop (); s.top (); s.empty (); s.size ();
Queue #include <queue>
默认的容器类型是deque,让双端队列展示队列的性质。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 queue<int > q; q.push (1 ); q.pop (); q.front (); q.back (); q.empty (); q.size ();
Set #include <set>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 set<int > s; s.insert (20 ); s.size (); set<int >::iterator it = s.begin (); for (it; it != s.end (); it++) { cout << *it << endl; } s.erase (20 ); s.clear (); bool exist = (s.find (20 ) != s.end ()); int count = s.count (20 )
Map #include <map>
红黑树实现,内部元素有序#include <unordered_map>
哈希实现,内部无序,查找更高效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 map<string, string> m; m.insert (make_pair ("key" , "value" )); m["key" ] = "value" ; string v = m.at ("key" ); m.size (); for (map<string, string>::iterator it=m.begin (); it != m.end (); it++) { cout << it->first << ": " << it->second << endl; } m.erase ("key" ); m.clear (); bool exist = (m.find ("key" ) != m.end ()); int count = m.count ("key" )