设置检测插入失败

011*_*110 4 c++ set stdset

有没有一种简单的方法来检测何时没有发生插入插入,因为插入的项目已经存在于集合中?例如,我想向用户显示一条消息,显示插入失败,以便他们可以更轻松地查找和删除其数据中的重复项.这里有一些伪代码来演示我想要做的事情:

try
{
   items.insert(item)
}

catch insert_failed_item_already_in_set
{
   // show user the failed item
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 16

签名set::insert是:

pair<iterator,bool> insert ( const value_type& x );
Run Code Online (Sandbox Code Playgroud)

所以,你的代码看起来像:

if( !items.insert(item).second )
{   
    show user the failed item
}
Run Code Online (Sandbox Code Playgroud)


Nim*_*Nim 11

有这个insert签名std::set

pair<iterator,bool> insert ( const value_type& x );

测试second返回的对,如果插入成功则应设置为true.


小智 5

作为设置插入返回对,您可以使用 get<1> 检查对的第二个元素的状态,这是 Boolean ,如果您的插入完成与否。

if (get<1>(set.insert(x)) == false){
 //Your error log.
}
Run Code Online (Sandbox Code Playgroud)