views:

42

answers:

2

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;
}
A: 

in STL there isn't, but boost offers this funcionality:

boost::algorithm::find_all

Yossarian
+3  A: 

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.

Charles Bailey