1

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;
}
paolo
  • 2,345
  • 1
  • 3
  • 17
Luistt0
  • 13
  • 2
  • You might be looking for [`std::views::filter(EvenNumber)`](https://en.cppreference.com/w/cpp/ranges/filter_view) – MSalters Jun 28 '22 at 08:38

1 Answers1

0

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))

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • `it+1` (which is what I'd normally use) or [`std::next(it)`](https://en.cppreference.com/w/cpp/iterator/next) (which I'd use if it helps the code be self-documenting). – Eljay Jun 28 '22 at 11:26
  • that's the perfect solution for my problem !!! the code runs correctly now. thank's alot – Luistt0 Jun 28 '22 at 16:12