检查元素是否在列表中(包含) [英] Check if element is in the list (contains)
问题描述
我有一个元素列表,例如整数,我想检查我的变量(另一个整数)是否为列表中的元素之一。在python中,我会这样做:
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:
my_list = [1,2,3,4] # elements
my_var = 3 # my variable
my_var in my_list # returns boolean
如何在C ++中做到这一点?我曾考虑使用 std :: list
,但是在其中找不到 find
方法。我可以在 std :: set
结构中看到这种方法。
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.
更深入地讲,问题在于我的程序是给定一些唯一的ID(一个列表,一个集合等),然后遍历一长串输入数据(ID),并检查它们是否包含在列表中(每个迭代步骤返回的布尔值)。而且我不确定在C ++中应该怎么做。
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++.
推荐答案
您可以使用 std: :find
bool found = (std::find(my_list.begin(), my_list.end(), my_var) != my_list.end());
您需要包括< algorithm>
。它应该可以在标准容器,向量列表等上工作。
You need to include <algorithm>
. It should work on standard containers, vectors lists, etc...
这篇关于检查元素是否在列表中(包含)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!