map insert 操作

来源:互联网 发布:国外个人java技术博客 编辑:程序博客网 时间:2024/06/06 01:27

map<string,int> m_map;

m_map.insert(map<string,int>::value_type("hello",5));

m_map.insert(make_pair("hello",5));

也就是说,insert后面的数据是pair类型或者是value_type类型了,然而对C++有了解的人都明白,其实value_type和pair<const k,v> 是等价的、insert() 中的参数必须是value_type类型,那么为什么insert()中的参数能够使用make_pair产生的pair<k,v>呢?

其实,因为我们在加入pair<k,v>时的k已经是常量了,所以可以加入。。。而正常来讲这都是所有编译器所能接受的。

在insert插入的同时,还有返回值来说明是否插入成功,就是pair<map<string,int>::iterator,bool>>类型,如本实例pair<map<string,int>::iterator,bool>> rent= m_map.insert(make_pair("hello",5));

rent->second即是成功与否的标志;rent->first就是返回的map<string,int>::iterator迭代器;rent->first.first就是string类型的数据。


exp: 计算单词的个数 (2种方法)

1.

map<string, int > word_count;

string word;

while( cin >> word )

{

       word_count[ word ] ++;

}

2.

map<string, int > word_count;

string word;

while(cin >> word)

{

     pair< map<string,int>::iterator, bool>  ret = word_count.insert(make_pair(word,1));

     if( !ret.second)

          ++ ret.first->second;     // 等价于++ ((ret.first)->second)

}