Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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;


	vecstr.push_back("aaaa");
	vecstr.push_back("bbbb");
	vecstr.push_back("zzzz");
	vecstr.push_back("bbbb");
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
	{
		public:
		strEqual(const string& str) : m_str(str)
		{}
		bool operator () (const string& str)
		{
			return m_str == str;
		}
		private:
		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
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap