C++ - Iterating over std::vector<> returned from find_if

// find_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::find_if
#include <vector>       // std::vector

bool IsOdd (int i) {
  return ((i%2)==1);
}

int main () {
  std::vector<int> myvector;

  myvector.push_back(10);
  myvector.push_back(25);
  myvector.push_back(40);
  myvector.push_back(55);


  std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd); 
  std::cout << "ODD values are: " << std::endl;     

  while(it != myvector.end() ){

    std::cout << *it  << " in position " << (it - myvector.begin())  << '\n';
    it = std::find_if (++it, myvector.end(), IsOdd); 
  }
  return 0;
}

EDIT: Changed it+1 to ++it see @David Rodríguez - dribeas comment below.


You can increment it and use it as a starting point to iterate further:

std::cout << "odd values: ";
auto it = myvector.begin();
while(it != myvector.end())
{
   it = std::find_if (it, myvector.end(), IsOdd);
   if(it == myvector.end()) break;
   std::cout << *it << ' ';
   ++it;
}
std::cout << endl;

A much more algorithm oriented approach, makes use of copy_if, having an output vector as a result container:

std::vector<int> results;
std::copy_if(myvector.begin(), myvector.end(), std::back_inserter(results), IsOdd);

Now results contains the odd values. (Note the back:inserter is in the <iterator> header)


You can find the index of a vector iterator (and, more generally, any random-access iterator) by subtracting the start of the sequence:

std::cout << "The index is " << (it - myvector.begin()) << '\n';

Even more generally, there is a std::distance function which can give you the distance between forward iterators. You could use that, for example, if your container were a list; but you probably wouldn't want to, since it would be much slower.

To find all the odd numbers, you'll need a loop to call find again, starting from the element after the one you just found.