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++?
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++?
Here 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;
}
To get similar syntax as in OP's question:
std::vector<int> x;
if ( count( x.begin(), x.end(), VAL_TO_FIND ) ) {
// found
} else {
// not found
}
There isn't a built-in function doing exactly that.
There is std::find
which comes close, but since it doesn't return a bool
it is a bit more awkward to use.
You could always roll your own, to get syntax similar to JIa3ep's suggestion, but without using count
(which always traverses the entire 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 simply do this to use it:
std::vector<int> x;
if (contains(x.begin(), x.end(), 4)) {...}
If the vector is ordered, you can also use std::binary_search.
std::binary_search(vec.begin(), vec.end(), 4) // Returns true or false