Home > other >  what is field 'predict' excatly means in (find_if )function in cpp?
what is field 'predict' excatly means in (find_if )function in cpp?

Time:06-28

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

CodePudding user response:

I was trying to use (find_if) function to display even numbers on the screen [...]

The std::find_if is a wrong tool for this; in fact, you don't need the std::find_if if you intend to print all the even elements.

You need instead a for-loop.

for (auto ele: v)
        if(EvenNumber(ele))
            std::cout << ele << " ";

That being said, if you meant to only print the first even digit in the vector of ints, you should have used simply a if statement:

auto it = std::find_if(v.begin(), v.end(), EvenNumber);
if (it != v.end())
    std::cout << *it << " ";

You don't require the std::sort for this operation, unless you need to find the smallest even number in the vector.


[...] but it gives me all elements in the vector...

It is because, you have iterated from the iterator pointed to the first (smallest) even digit in the sorted vector. Since 0 is the smallest and the first element in the sorted vector, you will see all the elements afterwords when you iterate.


Also note that following:

CodePudding user response:

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