如何检查一个元素是否在集合中?
是否有与以下代码更简单的等效代码:
myset.find(x) != myset.end()
如何检查一个元素是否在集合中?
是否有与以下代码更简单的等效代码:
myset.find(x) != myset.end()
当前回答
我能够为std::list和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
这样可以稍微清理一下语法。
但是我不能使用模板模板参数魔术使此工作任意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() ;
}
任何关于改进上一个答案的评论都是很好的。
其他回答
/ /通用语法
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.
}
另一种简单地判断元素是否存在的方法是检查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
}
从c++ 20开始,就有了bool std::contains(const K&) https://en.cppreference.com/w/cpp/container/set/contains
写你自己的:
template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
return container.find(elem) != container.end();
}
在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";
}
}