Searching for multiple elements using std::find()
Solution 1
You can't use std::find
. Assuming 0&&1&&D
is meant to be a list of three values and you're trying to find an element in the vector with any of those values, you can use:
std::find_if
with a predicate (a lambda may be easiest e.g.[](const T& x) { return x == 0 || x == 1 || x == d; }
, whereT
is whatever type yourvector
holds), orstd::find_first_of
(the linked page has a good example).
Solution 2
std::for_each
might work for you.
std::for_each(vector.begin(),
vector.end(),
[](auto& item) -> void {if (item == <xxx> ) { /* Use the item */ });
You asked in a comment:
This may be a separate question, but is there a method i can use to search in a vector if certain elements are present?
std::any_of
is the function for that.
bool found = std::any_of(vector.begin(),
vector.end(),
[](auto& item) -> bool { return item == <xxx>; });
Solution 3
The C++ Reference states it pretty clearly:
"An iterator to the first element in the range that compares equal to
val
. If no elements match, the function returnslast
."
So you can't do it with just one function call.
Noobgineer
Updated on June 04, 2022Comments
-
Noobgineer almost 2 years
Is it possible to use
std::find()
to search for multiple elements with 1 call? Example:std::find(vector.begin(), vector.end(), 0&&1&&D)
Thanks
-
Noobgineer about 8 yearsThis may be a seperate question, but is there a method i can use to search in a vector if certain elements are present? Or do i have to do it recursively?
-
Nacho about 8 yearsMight want to check Tony D's answer for that :)
-
Noobgineer about 8 yearsNot exactly, but close. What im trying to do is find if my vector contains all those of those elements, i.e.
vector[0] == 1
,vector[1] == 0
,vector[2]= = D
. Does not have to be in those exact positions, but assuming a vector with size i. Likewise, they dont have to be adjacent. -
Noobgineer about 8 yearsCould you explain the third parameter? what does
[](auto item) -> bool {return item == <xxx>l})
do? -
R Sahu about 8 yearsThat's a lambda function. See en.cppreference.com/w/cpp/language/lambda for further details.
-
Tony Delroy about 8 yearsThen you might as well put the 1, 0, D values into a second vector, and have a
for
loop over it callingfind
in the first vector for each of those values in turn. It might be less cache friendly if the second vector is much smaller than the first, but I've no reason to think you've enough data in a performance-critical part of your program to make that a practical concern. If you're determined to avoid that, you could usefind_first_of
, and each time a match is found remove the matching element from the set of values you're seeking, until it's empty (success) or you hitend
.