C++ 如何检查元素是否在 std::set 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1701067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check that an element is in a std::set?
提问by fulmicoton
How do you check that an element is in a set?
你如何检查一个元素是否在一个集合中?
Is there a simpler equivalent of the following code:
是否有一个更简单的等价于以下代码:
myset.find(x) != myset.end()
回答by unwind
The typical way to check for existence in many STL containers such as std::map
, std::set
, ... is:
在许多 STL 容器(例如std::map
, std::set
, ... )中检查是否存在的典型方法是:
const bool is_in = container.find(element) != container.end();
回答by Pieter
Another way of simply telling if an element exists is to check the count()
简单地判断元素是否存在的另一种方法是检查 count()
if (myset.count(x)) {
// x is in the set, count is 1
} else {
// count zero, i.e. x not in the set
}
Most of the times, however, I find myself needing access to the element wherever I check for its existence.
然而,大多数时候,我发现自己需要访问该元素,无论我在哪里检查它是否存在。
So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end
too.
所以无论如何我都必须找到迭代器。然后,当然,最好将它与end
太简单地进行比较。
set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
// do something with *it
}
C++ 20
C++ 20
In C++20 set gets a contains
function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245
在 C++20 中 set 获取一个contains
函数,因此如下所述成为可能:https: //stackoverflow.com/a/54197839/895245
if (myset.contains(x)) {
// x is in the set
} else {
// no x
}
回答by Tim
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:
只是为了澄清,contains()
在这些容器类型中没有像这样的成员的原因是因为它会让你编写低效的代码。这种方法可能只是在this->find(key) != this->end()
内部进行,但请考虑当密钥确实存在时您会做什么;在大多数情况下,你会想要获取元素并用它做一些事情。这意味着你必须做一个 second find()
,这是低效的。最好直接使用 find ,这样你就可以缓存你的结果,像这样:
auto it = myContainer.find(key);
if (it != myContainer.end())
{
// Do something with it, no more lookup needed.
}
else
{
// Key was not present.
}
Of course, if you don't care about efficiency, you can always roll your own, but in that case you probably shouldn't be using C++... ;)
当然,如果你不关心效率,你总是可以自己动手,但在这种情况下,你可能不应该使用 C++... ;)
回答by Denis Sablukov
In C++20we'll finally get std::set::contains
method.
在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";
}
}
回答by Sam Harwell
If you were going to add a contains
function, it might look like this:
如果您要添加一个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();
}
This works with std::set
, other STL containers, and even fixed-length arrays:
这适用于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));
}
Edit:
编辑:
As pointed out in the comments, I unintentionally used a function new to C++0x (std::begin
and std::end
). Here is the near-trivial implementation from VS2010:
正如评论中指出的那样,我无意中使用了 C++0x (std::begin
和std::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);
}
}
回答by Prashant Shubham
You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
您还可以在插入元素时检查元素是否在集合中。单元素版本返回一个pair,其成员pair::first 设置为一个迭代器,指向新插入的元素或集合中已有的等效元素。如果插入了新元素,则pair::second 元素设置为true,如果等效元素已存在,则设置为false。
For example: Suppose the set already has 20 as an element.
例如:假设集合已经有 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.
If the element is newly inserted than pair::first will point to the position of new element in set.
如果元素是新插入的,那么 pair::first 将指向集合中新元素的位置。
回答by stefaanv
Write your own:
自己写:
template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
return container.find(elem) != container.end();
}
回答by Manas Bondale
I use
我用
if(!my_set.count(that_element)) //Element is present...
;
But it is not as efficient as
但效率不如
if(my_set.find(that_element)!=my_set.end()) ....;
My version only saves my time in writing the code. I prefer it this way for competitive coding.
我的版本只节省了我编写代码的时间。我更喜欢以这种方式进行竞争性编码。
回答by sanjeev
//general Syntax
//通用语法
set<int>::iterator ii = find(set1.begin(),set1.end(),"element to be searched");
/* in below code i am trying to find element 4 in and int set if it is present or not*/
/* 在下面的代码中,我试图在元素 4 中找到元素 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.
}
回答by bobobobo
I was able to write a general contains
function for std::list
and std::vector
,
我能够contains
为std::list
and编写一个通用函数std::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
This cleans up the syntax a bit.
这稍微清理了语法。
But I could not use template template parameter magicto make this work arbitrary stl containers.
但是我不能使用模板模板参数魔术来使这个工作成为任意 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() ;
}
Any comments about improving the last answer would be nice.
关于改进最后一个答案的任何评论都会很好。