map 的插入方法 下标法 和 insert 法的区别

来源:互联网 发布:手机动态屏幕软件 编辑:程序博客网 时间:2024/04/29 23:25

出处:http://blog.csdn.net/yang_lang/article/details/6669101

对于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; // empty map from string to int
string word;
while (cin >> word) {
// inserts element with key equal to word and value 1;
// if word already in word_count, insert does nothing
pair<map<string, int>::iterator, bool> ret =
word_count.insert(make_pair(word, 1));
if (!ret.second) // word already in word_count
++ret.first->second; // increment counter
}

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

map<string,int> word_count;
int ccurs = word_count["foobar"];
但是,使用下标存在一个很危险的副作用:如果该键不在 map 容器中,那么下标操作会插入一个具有该键的新元素。
另外寻找元素是 "[]" 返回的是map中第二个元素的参考(如果key存在的话,不存在创建这个key).
而find()返回的是指向这个key的迭代器。
所以综合如上所述,用 insert()和find()是安全的做法,而用"[]"是不安全的。
0 0
原创粉丝点击