关闭

map

147人阅读 评论(0) 收藏 举报
分类:

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.
什么是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).

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

4、find, count, lower_bound, upper_bound, equal_range

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8104次
    • 积分:450
    • 等级:
    • 排名:千里之外
    • 原创:34篇
    • 转载:3篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论