Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Nov 30, 2004



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Using STL Binders

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:

	vector<string> vecstr;

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:

	class strEqual
		strEqual(const string& str) : m_str(str)
		bool operator () (const string& str)
			return m_str == str;
		string m_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:

	#include <functional>
	using namespace std;
	equal_to<string> Strequal

	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"));
bind1st binds the first agrument of the binary object with a value. bind2nd does the same with the second argument.

Saurabh Ramya
Thanks for your registration, follow us on our social networks to keep up-to-date