408

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

是否有以下代码的更简单等价物:

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

11 回答 11

496

在许多 STL 容器(例如std::map, std::set, ...)中检查是否存在的典型方法是:

const bool is_in = container.find(element) != container.end();
于 2009-11-09T13:49:27.747 回答
284

另一种简单判断元素是否存在的方法是检查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 
}
于 2009-11-09T15:42:31.233 回答
52

澄清一下,这些容器类型中没有类似成员的原因contains()是因为它会让您编写低效的代码。这种方法可能只是在this->find(key) != this->end()内部执行,但请考虑当密钥确实存在时您会做什么;在大多数情况下,您会想要获取该元素并对其进行处理。这意味着你必须做第二个find(),这是低效的。最好直接使用 find ,这样您就可以缓存结果,如下所示:

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

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

于 2009-11-09T16:26:59.380 回答
34

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";
    }
}
于 2019-01-15T11:20:27.167 回答
8

如果要添加一个contains函数,它可能如下所示:

#include <algorithm>
#include <iterator>

template<class TInputIterator, class T> inline
bool contains(TInputIterator first, TInputIterator last, const T& value)
{
    return std::find(first, last, value) != last;
}

template<class TContainer, class T> inline
bool contains(const TContainer& container, const T& value)
{
    // This works with more containers but requires std::begin and std::end
    // from C++0x, which you can get either:
    //  1. By using a C++0x compiler or
    //  2. Including the utility functions below.
    return contains(std::begin(container), std::end(container), value);

    // This works pre-C++0x (and without the utility functions below, but doesn't
    // work for fixed-length arrays.
    //return contains(container.begin(), container.end(), value);
}

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

这适用于std::set、其他 STL 容器,甚至是固定长度的数组:

void test()
{
    std::set<int> set;
    set.insert(1);
    set.insert(4);
    assert(!contains(set, 3));

    int set2[] = { 1, 2, 3 };
    assert(contains(set2, 3));
}

编辑:

正如评论中所指出的,我无意中使用了 C++0x (std::beginstd::end) 的新函数。这是来自 VS2010 的近乎微不足道的实现:

namespace std {

template<class _Container> inline
    typename _Container::iterator begin(_Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());
    }

template<class _Container> inline
    typename _Container::const_iterator begin(const _Container& _Cont)
    { // get beginning of sequence
    return (_Cont.begin());
    }

template<class _Container> inline
    typename _Container::iterator end(_Container& _Cont)
    { // get end of sequence
    return (_Cont.end());
    }

template<class _Container> inline
    typename _Container::const_iterator end(const _Container& _Cont)
    { // get end of sequence
    return (_Cont.end());
    }

template<class _Ty,
    size_t _Size> inline
    _Ty *begin(_Ty (&_Array)[_Size])
    { // get beginning of array
    return (&_Array[0]);
    }

template<class _Ty,
    size_t _Size> inline
    _Ty *end(_Ty (&_Array)[_Size])
    { // get end of array
    return (&_Array[0] + _Size);
    }

}
于 2009-11-09T16:36:26.480 回答
4

您还可以在插入元素时检查元素是否在集合中。单元素版本返回一个对,其成员 pair::first 设置为一个迭代器,指向新插入的元素或集合中已有的等效元素。如果插入了新元素,则对中的 pair::second 元素设置为 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.

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

于 2016-09-15T17:42:01.297 回答
1

我用

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

但效率不如

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

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

于 2018-02-03T10:35:51.233 回答
1

从 C++20 开始,就有了简单的(最后!)bool std::contains(const K&) https://en.cppreference.com/w/cpp/container/set/contains

于 2021-11-01T07:18:13.980 回答
0

自己写:

template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
  return container.find(elem) != container.end();
}
于 2009-11-09T13:59:28.913 回答
0

我能够为and编写一个通用contains函数,std::liststd::vector

template<typename T>
bool contains( const list<T>& container, const T& elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

template<typename T>
bool contains( const vector<T>& container, const T& elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

// use:
if( contains( yourList, itemInList ) ) // then do something

这稍微清理了语法。

但是我不能使用模板模板参数魔术来使这项工作成为任意 stl 容器。

// NOT WORKING:
template<template<class> class STLContainer, class T>
bool contains( STLContainer<T> container, T elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

关于改进最后一个答案的任何评论都会很好。

于 2013-05-04T19:17:59.500 回答
-1

//一般语法

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

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

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.
 }
于 2017-09-04T11:27:13.487 回答