I have a set of numbers:
{2, 6, 8}
I would like to check if any of these numbers are in my vector:
std::vector<int> myVector;
I know that I can check for each individually using algorithm's std::find:
auto iter1 = std::find(myVector.begin(), myVector.end(), 2);
auto iter2 = std::find(myVector.begin(), myVector.end(), 6);
auto iter3 = std::find(myVector.begin(), myVector.end(), 8);
if(iter1 != myVector.end() || iter2 != myVector.end() || iter3 != myVector.end())
std::cout << "A desired value was found in the vector!"
In this example, there are only three numbers but the real set of numbers is going to be larger. Also, this seems kind of tedious. Is there a better solution?
You can use std::find_first_of
:
std::vector<int> myVector = /* something */;
std::vector<int> values = {2, 6, 8};
auto first_found = std::find_first_of(std::begin(myVector), std::end(myVector),
std::begin(values), std::end(values));
if (first_found != std::end(myVector)) {
// Found one of them!
}