map

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.

1、insert方法：
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++)
cout<<it->second<<endl;

2、erase方法：
(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.

Essentially amortised time means “average time taken per operation, if you do many operations”.

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).

3、Observers:
(1) key_comp:
(2) value_comp:

4、find, count, lower_bound, upper_bound, equal_range

• 本文已收录于以下专栏：

举报原因： 您举报文章：map 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)