原创 2015年07月10日 14:37:59

map: associative containers, key-value.
the keys are generally used to sort and uniquely identify the elements, while the mapped values are content associated to this key.

my_map.insert(it, val) //it:iterator, val:pair value
another_map.insert(my_map.begin(), my_map.end())
if a single element is inserted, logarithmic in size in general, but amortized constant if a hint is given and the position given is the optimal.
C++11: if N elements are inserted, Nlog(size+N).

 map<int, string> my_map;
    my_map.insert(my_map.begin(), pair<int, string>(3,"apple"));
    my_map.insert(my_map.begin(), pair<int, string>(2,"pear"));
    my_map.insert(my_map.begin(), pair<int, string>(1,"orange"));
    cout<<"my_map contains:"<<endl;
    for(auto i:my_map){   //i是pair
        cout<<i.first<<"  "<<i.second<<endl;
    cout<<"another_map contains:"<<endl;
    map<int, string> another_map;
    another_map.insert(my_map.begin(), my_map.end());
    for(map<int, string>::iterator it = another_map.begin(); it != another_map.end(); it++)

(a) erasing by iterator: my_map.erase( it )
(b) erasing by key: my_map.erase( key )
(c) erasing by range: my_map.erase( it1, it2 )
(a) For the first version (erase(position)), amortized constant.
(b) For the second version (erase(val)), logarithmic in container size.
(c) For the last version (erase(first,last)), linear in the distance between first and last.
什么是amortied constant?:
Essentially amortised time means “average time taken per operation, if you do many operations”.
动态序列插入例子:dynamic array
repeatedly add new items. Normally adding an item takes constant time (that is, O(1)). But each time the array is full, you allocate twice as much space, copy your data into the new region, and free the old space. Assuming allocates and frees run in constant time, this enlargement process takes O(n) time where n is the current size of the array.

So each time you enlarge, you take about twice as much time as the last enlarge. But you’ve also waited twice as long before doing it! The cost of each enlargement can thus be “spread out” among the insertions. This means that in the long term, the total time taken for adding m items to the array is O(m), and so the amortised time (i.e. time per insertion) is O(1).

(1) key_comp:
(2) value_comp:

4、find, count, lower_bound, upper_bound, equal_range