如何检查一个元素是否在集合中?

是否有与以下代码更简单的等效代码:

myset.find(x) != myset.end()

当前回答

我使用

if(!my_set.count(that_element)) //Element is present...
;

但它的效率不如

if(my_set.find(that_element)!=my_set.end()) ....;

我的版本只是节省了我写代码的时间。对于竞争性编码,我更喜欢这种方式。

其他回答

您还可以在插入元素时检查元素是否在set中。 单元素版本返回一个pair,其成员pair::first set指向一个迭代器,该迭代器要么指向新插入的元素,要么指向集合中已经存在的等效元素。如果插入了新元素,pair中的第二个元素将被设置为true,如果已经存在等效元素则为false。

例如:假设集合中已经有20作为元素。

 std::set<int> myset;
 std::set<int>::iterator it;
 std::pair<std::set<int>::iterator,bool> ret;

 ret=myset.insert(20);
 if(ret.second==false)
 {
     //do nothing

 }
 else
 {
    //do something
 }

 it=ret.first //points to element 20 already in set.

如果元素是新插入的,则than pair::first将指向新元素在set中的位置。

就是这个,一英里。

bool once(uintptr_t val) {
    return visited.emplace(val).second;
}

怎么会不是这样呢?

https://godbolt.org/z/9zP77jqMc

func5(unsigned long):
        sub     rsp, 24
        mov     QWORD PTR [rsp+8], rdi
        lea     rsi, [rsp+8]
        mov     edi, OFFSET FLAT:visited2
        call    std::pair<std::_Rb_tree_iterator<unsigned long>, bool> std::_Rb_tree<unsigned long, unsigned long, std::_Identity<unsigned long>, std::less<unsigned long>, std::allocator<unsigned long> >::_M_emplace_unique<unsigned long&>(unsigned long&)
        add     rsp, 24
        mov     eax, edx
        ret

/ /通用语法

       set<int>::iterator ii = find(set1.begin(),set1.end(),"element to be searched");

/*在下面的代码中,我试图找到元素4和int集,如果它存在与否*/

set<int>::iterator ii = find(set1.begin(),set1.end(),4);
 if(ii!=set1.end())
 {
    cout<<"element found";
    set1.erase(ii);// in case you want to erase that element from set.
 }

在c++ 20中,我们最终得到std::set::contains方法。

#include <iostream>
#include <string>
#include <set>

int main()
{
    std::set<std::string> example = {"Do", "not", "panic", "!!!"};

    if(example.contains("panic")) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }
}

另一种简单地判断元素是否存在的方法是检查count()

if (myset.count(x)) {
   // x is in the set, count is 1
} else {
   // count zero, i.e. x not in the set
}

然而,大多数时候,我发现自己需要访问元素,无论我在哪里检查它的存在。

所以我还是要找到迭代器。当然,最好也把它和end进行比较。

set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
   // do something with *it
}

C + + 20

在c++ 20中,set获得一个contains函数,因此如下所述成为可能:https://stackoverflow.com/a/54197839/895245

if (myset.contains(x)) {
  // x is in the set
} else {
  // no x 
}