What does field 'predicate' exactly mean in (find_if) function in cpp?

Viewed 68

I'm a beginner in c++. I was learning STL especially vectors & iterators uses..I was trying to use (find_if) function to display even numbers on the screen.I knew that I have to return boolean value to the third field in the function(find_if) ..but it gives me all elements in the vector !!! .but,When I used the function (GreaterThanThree) the code outputs the right values without any problem. this is my code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool EvenNumber(int i)
{
        return i%2==0
}
/*bool GreaterThanThree(int s)
{
  return s>3;
}
*/
int main()
{
    vector <int> v={2,1,4,5,0,3,6,7,8,10,9};
    sort(v.begin(),v.end());
     auto it= find_if(v.begin(),v.end(),EvenNumber);
     for(;it!=v.end();it++)
     {
         cout<<*it<<" ";
     }
    return 0;
}
1 Answers

You can use std::find_if, but each call finds only one element (at best). That means you need a loop. The first time, you start at v.begin(). This will return the iterator of the first even element. To find the second even element, you have to start the second find_if search not at v.begin(), but after (+1) the first found element.

You should stop as soon as std::find_if returns v.end(), which could even be on the first call (if all elements are odd). I.e. for(auto it = std::find_if(v.begin(), v.end(), EvenNumber); it != v.end(); it = std::find_if(it+1, v.end(); EvenNumer))

Related