Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative version of find_if which finds all, not just the first?

Tags:

c++

iterator

stl

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;
}
like image 933
Frank Avatar asked Feb 26 '10 20:02

Frank


People also ask

What does Find_if return if not found?

First of all, what does find_if return? It returns an iterator to the first element of the searched range that satisfies the condition. If there is no such item, it returns an iterator pointing beyond the last element, in other words, to end() .

How do you find a vector of something?

You can use the find function, found in the std namespace, ie std::find . You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.

What is Find_if C++?

C++ find_if() function is part of standard library which tries to search or find for the very first element to be encountered for satisfying condition specified by the algorithmic function.

What does find return if not found C++?

The find() function returns an iterator that points to the val in the specified range. If the value is not found, then it returns an iterator to the last of the array or vector.


2 Answers

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.

like image 196
CB Bailey Avatar answered Oct 18 '22 23:10

CB Bailey


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

boost::algorithm::find_all

like image 38
nothrow Avatar answered Oct 18 '22 23:10

nothrow