STL中map的成员函数insert的返回值

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;
}

转处:https://blog.csdn.net/maocl1983/article/details/5391509

原文地址:https://www.cnblogs.com/laohaozi/p/12537852.html