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
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.
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++.
Use
std::find
, something like:Declare additional helper function like this:
And use it like this:
Snapshot of example can be found here:
https://github.com/tapika/cppscriptcore/blob/b7f3d62747494a52a440482e841ffb016a3fc56e/SolutionProjectModel/Project.cpp#L13
They really should add a wrapper. Like this:
std::list
does not provide a search method. You can iterate over the list and check if the element exists or usestd::find
. But I think for your situationstd::set
is more preferable. The former will takeO(n)
time but later will takeO(lg(n))
time to search.You can simply use:
you must
#include <algorithm>
, then you can use std::findYou can use
std::find
You need to include
<algorithm>
. It should work on standard containers, vectors lists, etc...