11

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

try
{
   items.insert(item)
}

catch insert_failed_item_already_in_set
{
   // show user the failed item
}
4

8 回答 8

21

签名为set::insert

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

因此,您的代码如下所示:

if( !items.insert(item).second )
{   
    show user the failed item
}
于 2012-03-06T15:12:58.900 回答
12

里面有这个insert签名std::set

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

测试second返回的pair,如果插入成功,应该设置为true。

于 2012-03-06T15:10:25.797 回答
6

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

if (get<1>(set.insert(x)) == false){
 //Your error log.
}
于 2014-01-17T11:33:11.090 回答
4

来自cplusplus

指插入(常量 T& 值)

第一个版本返回一个对,其成员 pair::first 设置为一个迭代器,指向新插入的元素或集合中已经具有相同值的元素。如果插入了新元素,则对中的 pair::second 元素设置为 true,如果存在具有相同值的元素,则设置为 false。

于 2012-03-06T15:12:00.570 回答
3

如果元素被成功插入,STLset<>.insert(elem)返回pair<iterator,bool>对中第二个值的位置,否则返回 false。true

于 2012-03-06T15:14:39.460 回答
1

对集合的插入操作返回一个对,其成员first集指向一个迭代器,该迭代器指向新插入的元素或集合中已有的等效元素。如果插入了新元素或已存在等效元素second,则该对中的元素设置为。因此,您可以使用该元素来确定它是否被添加。truefalsesecond

例如:

#include <iostream>
#include <set>
using namespace std;
int main ()
{
 std::set<int> myset;
 std::set<int>::iterator it;
 std::pair<std::set<int>::iterator,bool> ret;


 for (int i=1; i<=5; ++i) myset.insert(i*10);    // set: 10 20 30 40 50

 ret = myset.insert(20);               // no new element inserted

 if (ret.second==false)
     cout<<"Element already present";

}
于 2016-08-02T12:44:21.583 回答
0

因为集合容器不允许重复值,所以插入操作会检查每个插入的元素是否在容器中已经存在具有相同值的另一个元素,如果存在,则不插入该元素并且 - 如果函数返回值 - 一个迭代器归还给它。

你可以在这里找到一个例子: http ://www.cplusplus.com/reference/stl/set/insert/

于 2012-03-06T15:14:05.623 回答
0

检查一个项目是否已经在一个集合中很容易。如果这是您要寻找的唯一东西,则无需尝试/捕获。

if ( items.find(item) == items.end() )
{
    // Item was not in the set, so put it in the set
    items.insert(item)
}
else
{
    // Item was already in the set
}

或者您可以检查插入的返回值,这是一对,其中second一半是插入是否成功:

if ( false == items.insert(item).second )
{
    // Item was already in the set
}

在这两种方法中,第二种方法更紧凑,更高效,因为第一种方法需要两次查找,一个 during .find,另一个 during .insert

于 2012-03-06T15:50:05.967 回答