http://hi.baidu.com/tiger_tnt/blog/item/3e6be9b5609ddcca36d3caa9.html
map在进行插入的时候是不允许有重复的键值的,如果新插入的键值与原有的键值重复则插入无效,可以通过insert的返回值来判断是否成功插入。下面是insert的函数原型:
pair<iterator, bool> insert(const value_type& x);
可以通过返回的pair中第二个bool型变量来判断是否插入成功。下面是代码:
#include <map>
#include <iostream>
int main(){
std::map< int,int > ll;
ll.insert( std::pair< int,int >(1,2) );
std::pair< std::map< int,int >::iterator,bool > ret;
ret=ll.insert( std::pair< int,int >(1,3) );
if( ret.second ){
std::cout<<"成功"<<std::endl;
}
else{
std::cout<<"失败"<<std::endl;
}
return 0;
}
本文介绍 C++ STL 中 map 容器的插入方法及其返回值的意义,通过示例展示了如何判断插入是否成功。
1万+

被折叠的 条评论
为什么被折叠?



