An alternative version of find_if that finds everything, not just the first?

Is there an alternative version of std::find_if that returns an iterator over all found elements, and not just the first?

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; } 
+4
source share
3 answers

You can simply use the 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 in a functor (perform the action only if the condition is true) and just use std::foreach .

+5
source

there is no STL, but boost offers this functionality:

boost :: algorithm :: find_all

+1
source

First, always try to come up with a typical use of STL, you can go for a raise. Here is a more simplified form from Charles's above answer.

  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; } 
0
source

Source: https://habr.com/ru/post/1302532/


All Articles