C++ 检查元素是否在列表中(包含)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24139428/
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
Check if element is in the list (contains)
提问by ducin
I've got a list of elements, say, integers and I want to check if my variable (another integer) is one of the elements from the list. In python I'd do:
我有一个元素列表,比如整数,我想检查我的变量(另一个整数)是否是列表中的元素之一。在 python 中,我会这样做:
my_list = [1,2,3,4] # elements
my_var = 3 # my variable
my_var in my_list # returns boolean
How to do that in C++? I thought of using std::list
, but I can find no find
method in it. I can see such method in std::set
structure.
如何在 C++ 中做到这一点?我想使用std::list
,但我找不到其中的find
方法。我可以在std::set
结构上看到这样的方法。
More deeply, the problem is that my program is given some unique ids (a list, a set, whatever) and I iterate over a long list of input data (ids) and check if they are included in the list (boolean value returned for each iteration step). And I'm not sure how should I do that in C++.
更深入地说,问题是我的程序被赋予了一些唯一的 id(一个列表、一个集合,等等),我遍历一长串输入数据(id)并检查它们是否包含在列表中(返回的布尔值)每个迭代步骤)。而且我不确定我应该如何在 C++ 中做到这一点。
回答by Matzi
You can use std::find
您可以使用 std::find
bool found = (std::find(my_list.begin(), my_list.end(), my_var) != my_list.end());
You need to include <algorithm>
. It should work on standard containers, vectors lists, etc...
您需要包括<algorithm>
. 它应该适用于标准容器、向量列表等...
回答by Rakib
std::list
does not provide a search method. You can iterate over the list and check if the element exists or use std::find
. But I think for your situation std::set
is more preferable. The former will take O(n)
time but later will take O(lg(n))
time to search.
std::list
不提供搜索方法。您可以遍历列表并检查元素是否存在或使用std::find
. 但我认为对于你的情况std::set
更可取。前者需要O(n)
时间,但后者需要O(lg(n))
时间进行搜索。
You can simply use:
您可以简单地使用:
if(mySet.find(myVar) != mySet.end()){
//do whatever
}
回答by Radu Chivu
回答by KungPhoo
They really should add a wrapper. Like this:
他们真的应该添加一个包装器。像这样:
namespace std
{
template<class _container,
class _Ty> inline
bool contains(_container _C, const _Ty& _Val)
{return std::find(_C.begin(), _C.end(), _Val) != _C.end(); }
};
...
if( std::contains(my_container, what_to_find) )
{
}
回答by Paul Evans
Use std::find
, something like:
使用std::find
,类似于:
if (std::find(std::begin(my_list), std::end(my_list), my_var) != std::end(my_list))
// my_list has my_var
回答by TarmoPikaro
Declare additional helper function like this:
像这样声明额外的辅助函数:
template <class T, class I >
bool vectorContains(const vector<T>& v, I& t)
{
bool found = (std::find(v.begin(), v.end(), t) != v.end());
return found;
}
And use it like this:
并像这样使用它:
void Project::AddPlatform(const char* platform)
{
if (!vectorContains(platforms, platform))
platforms.push_back(platform);
}
Snapshot of example can be found here:
示例快照可以在这里找到: