C++ STL
Vector
[ | | | | =>- [Fast] Insert at back: O(1)
- [Slow] Insert in beginning or middle: O(n)
- [Slow] Search: O(n)
- #include <vector>
- vector<int> vec;
- vec.push_back(5);
- vec.at(0); //Throws range_error exception
- vec.empty(); //bool Check if empty
- vec.size();
- vector<int> vec2(vec); // Copy constructor copies vec into vec2
- vec.clear();
- vec.swap(vec2);
- for(vector<int>::iterator itr = vec.begin(); itr!=vec.end(); itr++){
- cout << *itr << endl; // *itr gives value stored
- }
- for(auto it:vec) // Use &it for reference, if one wants changes in values
- cout << it << endl;
Deque
<= | | | | =>- [Fast] Insert at front and back: O(1)
- [Slow] Insert in middle: O(n)
- [Slow] Search: O(n)
- #include<deque>
- deque<int> deq = {4,6,7};
- deq.push_front(3);
- deq.push_back(8);
List
[ ] <-> [ ] <-> [ ]- [Fast] Insert and Remove anywhere: O(1)
- [Slow] Search: O(n)
- #include<list>
- list<int> listt = {5,2,9};
- listt.push_back(2);
- listt.push_front(1);
- list<int>::iterator itr = find(listt.begin(), listt.end(),2); //itr -> 2
- listt.insert(itr, 8); // Inserts in front of itr
- itr++
- listt.erase(itr)
- list1.splice(itr,list2,itr_a,itr_b);
Array
Thin layer around the naked array.- int a[3] = {3,4,5};
- array<int,3> a = {3,4,5}; // Array container of type (int,3)
- Size is fixed : array<int,fixed_size>;
- array<int,3> and array<int,4> are different types.
- a.swap();
- a.size();
- a.begin();
- a.end();
Set
- [Slow] Insert O(log(n))
- [Fast] Search O(log(n))
- Non duplicate data
- Value of elements cannot be modified
- #include<set>
- set<int> myset;
- myset.insert(2);
- set<int>::iterator it;
- it = myset.find(7);
- pair<set<int>::iterator, bool> ret; // ret.second='false' if already exists
- ret = myset.insert(3);
- myset.insert(itr,9);
Erase
- myset.erase(itr);
- myset.erase(7); // By value!
Multiset
- [Fast] Search O(log(n))
- [Slow] Traversing
- A set that allows duplicate items
- Value of elements cannot be modified
- multiset<int> myset;
Map
- [Fast] Find O(log(n))
- No duplicate key
- Keys cannot be modified
- Type of itr: pair<char,int>
- map<char,int> mymap;
- mymap.insert(pair<char,int>('a',100));
- mymap.insert(make_pair('z',200));
- mymap.insert(itr,pair<char,int>('a',300)); // itr is a hint.
Multimap
- Allows duplicate keys
- Keys cannot be modified
- Type of itr: pair<char,int>
- (*itr).first = 'd'; // Error