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++.
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.
We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1. count(s) if count > 0: print(f'{s} is present in the list for {count} times.
if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));
In & Not in operators“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.
You can use 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...
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.
You can simply use:
int my_var = 3;
std::set<int> mySet {1, 2, 3, 4};
if(mySet.find(myVar) != mySet.end()){
//do whatever
}
you must #include <algorithm>
, then you can use std::find
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) )
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With