Reputation: 66214
Is there an alternative version of std::find_if
that returns an iterator over all found elements, instead of just the first one?
Example:
bool IsOdd (int i) {
return ((i % 2) == 1);
}
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
std::vector<int>::iterator it = find_if(v.begin(), v.end(), IsOdd);
for(; it != v.end(); ++it) {
std::cout << "odd: " << *it << std::endl;
}
Upvotes: 8
Views: 5087
Reputation: 21
First always try to come up with typical STL usage itself, you can go for boost as well. Here is more simplified form from the above mentioned answer by Charles.
vec_loc = find_if(v3.begin(), v3.end(), isOdd);
if (vec_loc != v3.end())
{
cout << "odd elem. found at " << (vec_loc - v3.begin()) << "and elem found is " << *vec_loc << endl;
++vec_loc;
}
for (;vec_loc != v3.end();vec_loc++)
{
vec_loc = find_if(vec_loc, v3.end(), isOdd);
if (vec_loc == v3.end())
break;
cout << "odd elem. found at " << (vec_loc - v3.begin()) << "and elem found is " << *vec_loc << endl;
}
Upvotes: 0
Reputation: 792497
You can just use a for
loop:
for (std::vector<int>:iterator it = std::find_if(v.begin(), v.end(), IsOdd);
it != v.end();
it = std::find_if(++it, v.end(), IsOdd))
{
// ...
}
Alternatively, you can put your condition and action into a functor (performing the action only if the condition is true) and just use std::foreach
.
Upvotes: 11