You can use STL binders to use binary function objects as unary function objects in many STL algorithms which need them.
Suppose you need to find the count of strings in a vector of strings who are equal to a certain strings:
You need to find out how many elements of this vector are equal to bbbb
. The easy and straightforward approach is to use the count_if()
algorithm and use a function object as defined below as the algorithm's third argument:
strEqual(const string& str) : m_str(str)
bool operator () (const string& str)
return m_str == str;
and use it in count_if() as follows
int cnt = count_if(vecstr.begin(), vecstr.end(), strEqual("bbbb"));
The STL library gives some pre-defined function objects to be used in an STL algorithm. One of them is equal_to()
. You can use this algorithm in this way:
using namespace std;
bool b = Strequal("bbbb", "abbb");
For equal strings it will return 1 otherwise 0.
The problem with using equal_to()
in the first example is that it's a binary function object, and therefore needs two arguments. What you need is to keep the reference of the string and later on count_if()
invokes a function object, passes the elements of the container to it one by one and then allows the function object to return true or false by comparing the element of vector and the string you have kept as references:
1- count_if() needs an unary function object (takes one arguent)
2- equal_to() is a binary function object.
This is where binders come in. A binder converts the binary object into a unary object by binding one of the arguments of a binary object with a value.
You can achieve the same result using binders and a pre-defined function object that you achieved with your own function object:
int cnt = cnt = count_if(vecstr.begin(), vecstr.end(), bind1st(equal_to(), "bbbb"));
binds the first agrument of the binary object with a value. bind2nd
does the same with the second argument.