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

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

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

当前回答

写你自己的:

template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
  return container.find(elem) != container.end();
}

其他回答

另一种简单地判断元素是否存在的方法是检查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 
}

写你自己的:

template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
  return container.find(elem) != container.end();
}

Just to clarify, the reason why there is no member like contains() in these container types is because it would open you up to writing inefficient code. Such a method would probably just do a this->find(key) != this->end() internally, but consider what you do when the key is indeed present; in most cases you'll then want to get the element and do something with it. This means you'd have to do a second find(), which is inefficient. It's better to use find directly, so you can cache your result, like so:

auto it = myContainer.find(key);
if (it != myContainer.end())
{
    // Do something with it, no more lookup needed.
}
else
{
    // Key was not present.
}

当然,如果你不关心效率,你总是可以自己滚动,但在这种情况下,你可能不应该使用c++…;)

我使用

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

但它的效率不如

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

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

从c++ 20开始,就有了bool std::contains(const K&) https://en.cppreference.com/w/cpp/container/set/contains