Any built-in function to check if 4 is in [1,2,3,4] (vector)

In Ruby, I can do:

[1,2,3,4].include?(4) #=>True 

In Haskell, I can do:

 4 `elem` [1,2,3,4] #=> True 

What should I do in C ++?

+4
source share
5 answers

There is no built-in function that does just that. There is std::find which is close, but since it does not return bool , it is a little more inconvenient to use.

You can always use your own to get a syntax similar to the JIa3ep clause, but without using count (which always goes through the whole sequence):

 template <typename iter_t> bool contains(iter_t first, iter_t last, typename iter_t::value_type val){ return find(first, last, val) != last; } 

Then you can just do this to use it:

 std::vector<int> x; if (contains(x.begin(), x.end(), 4)) {...} 
+8
source

Here is an example using find:

 #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> Num(4); //insert values Num[0]=1; Num[1]=2; Num[2]=3; Num[3]=4; std::vector<int>::iterator p = find(Num.begin(), Num.end(), 4); if (p == Num.end()) std::cout << "Could not find 4 in the vector" << std::endl; else std::cout << "Have found 4 in the vector" << std::endl; return 0; } 
+20
source

If the vector is ordered, you can also use std :: binary_search.

 std::binary_search(vec.begin(), vec.end(), 4) // Returns true or false 
+2
source

To get the same syntax as in the OP question:

 std::vector<int> x; if ( count( x.begin(), x.end(), VAL_TO_FIND ) ) { // found } else { // not found } 
+1
source

You can use std :: set. This has a find () method.

0
source

All Articles