How to use find_if with bind with greater

· Read in about 2 min · (223 Words)
C++

Today I decided to show an example usage of std::find_if with std::bind. The task at hand is to find the first integer number in a vector that is greater than 10. The source code below shows three separate calls to find_if:

  • First one is compatible with C++ 98. It is using the std::bind2nd() which is now deprecated after the C++ 11 standard.
  • The second option uses a C++ 11 lambda function. Using it is very clear what is going on.
  • The third option uses the new std::bind() in a similar way that bind2nd was used in the first case.
#include <vector>
#include <algorithm>
#include <xfunctional>
#include <functional>
#include <iostream>
using namespace std;
using namespace std::placeholders;

int main()
{
    // C++ 11 only - for clarity to avoid multiple lines with push_back
    vector<int> v{ 1, 5, 6, 7, 11, 22, 33, 44, 3, 2, 1 };

    // using bind2nd (C++ 98)
    vector<int>::iterator I2 = std::find_if(v.begin(), v.end(), bind2nd(greater<int>(), 10));
    cout << *I2 << endl;

    // using a lambda function (C++ 11)
    auto I = find_if(v.begin(), v.end(), [](int a) { return a &gt; 10; });
    cout << *I << endl;

    // using bind (C++ 11)
    auto I3 = std::find_if(v.begin(), v.end(), bind(std::greater<int>(), _1, 10));
    cout << *I3 << endl;

    return 0;
}

That’s it. Similarly any other algorithms and functors can be used in the same way.