STL map 插入

Posted on 2011-12-20 02:30  无忧consume  阅读(378)  评论(0编辑  收藏  举报

对于STL中的map,插入有两种方法:
1、map <int,int>a;
     a[1 ]=1   //此方法初始化a[1],并给a[1]赋值。
     a[1]=2   //此方法修改了a[1的值。
2 map <int,int>a;
    a.insert(map<int,int>::value_type(1,1)); //此方法初始化a[1],并给a[1]赋值。
   a.insert(map<int,int>::value_type(1,2)); //因为a[1]已经存在,此方法不能初始化a[1],也不能修改a[1]的值。
3 特别注意的是,因为[ ]被重载为,如果不存在该key的值,则创建该对象,所以,一下操作比较危险。
    map<string,int> word_count;
    int ccurs = word_count["foobar"];//键“foobar”不在 map 容器中,那么下标操作会插入一个具有该键的新元素。

map 对象中一个给定键只对应一个元素。如果试图插入的元素所对应的键已在容器中,则 insert 将不做任何操作。含有一个或一对迭代器形参的 insert 函数版本并不说明是否有或有多少个元素插入到容器中。

但是,带有一个键-值 pair 形参的 insert 版本将返回一个值:包含一个迭代器和一个 bool 值的 pair 对象,其中迭代器指向 map 中具有相应键的元素,而 bool 值则表示是否插入了该元素。如果该键已在容器中,则其关联的值保持不变,返回的 bool 值为 true。在这两种情况下,迭代器都将指向具有给定键的元素。下面是使用 insert 重写的单词统计程序:

//count number of times each word occurs in the input
map<string, int> word_count; //emptymapfrom string toint
string word;
while (cin >> word) {
//inserts element with key equal towordand value1;
//ifwordalready inword_count,insertdoes nothing
pair<map<string, int>::iterator, bool> ret =
word_count.insert(make_pair(word, 1));
if (!ret.second) //wordalready inword_count
++ret.first->second; //increment counter
}

下标操作符给出了读取一个值的最简单方法:

map<string,int> word_count;
int ccurs = word_count["foobar"];
但是,使用下标存在一个很危险的副作用:如果该键不在map容器中,那么下标操作会插入一个具有该键的新元素。

Copyright © 2024 无忧consume
Powered by .NET 8.0 on Kubernetes