Check if the item is in the list (contains)

I have 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 would do:

my_list = [1,2,3,4] # elements my_var = 3 # my variable my_var in my_list # returns boolean 

How to do it in C ++? I was thinking about using std::list , but there is no find method in it. I see such a method in the std::set structure.

More deeply, the problem is that my program is given some unique identifiers (list, set, etc.), 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 to do this in C ++.

+21
c ++ contains
Jun 10 '14 at 11:05
source share
4 answers

You can use std::find

 bool found = (std::find(my_list.begin(), my_list.end(), my_var) != my_list.end()); 

You need to enable <algorithm> . It should work with standard containers, lists of vectors, etc.

+36
Jun 10 '14 at 11:08
source share

std::list does not provide a search method. You can iterate over the list and check if the item exists or use std::find . But I think std::set preferable for your situation. The first will take O(n) time, but later it will take O(lg(n)) time to search.

You can simply use:

 if(mySet.find(myVar) != mySet.end()){ //do whatever } 
+11
Jun 10 '14 at 11:09
source share

you must #include <algorithm> , then you can use std :: find

+3
Jun 10 '14 at 11:07
source share

Use std::find , something like:

 if (std::find(std::begin(my_list), std::end(my_list), my_var) != std::end(my_list)) // my_list has my_var 
+1
Jun 10 '14 at 11:10
source share



All Articles