Jump to content



how to use STL bind

  • You cannot reply to this topic
2 replies to this topic

#1 sfx81   Members   -  Reputation: 122

Like
0Likes
Like

Posted 03 February 2012 - 12:17 AM

Hi All,
I am trying to understand and use stl bind2nd, but getting compiler error. Could some one please identify as what I am doing wrong.
Any help will be appreciated.
Thanks Kaz.
#include <functional>
#include <algorithm>
#include <vector>
int MyIntCounter = 0;
class MyInt
{
int mId;
public:
MyInt():mId(++MyIntCounter){}
MyInt(int arg):mId(arg){}
bool operator()(const MyInt& rhs1 , const MyInt& rhs2)
{
return rhs1.mId == rhs2.mId == mId;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<MyInt> ints;
for(int i = 0; i < 10; ++i) ints.push_back( MyInt() );
MyInt finder2(2), finder3(3);
std::find_if( ints.begin(), ints.end(),
std::bind2nd(finder2, finder3 ) );
return 0;
}


Ad:

#2 Washu   Senior Moderators   -  Reputation: 2447

Like
0Likes
Like

Posted 03 February 2012 - 12:26 AM

what is your compiler error?
In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
ScapeCode - Blog | SlimDX

#3 Washu   Senior Moderators   -  Reputation: 2447

Like
1Likes
Like

Posted 03 February 2012 - 12:41 AM

First off, your object needs to be derived from std::binary_function, if you expect std::bind1st/std::bind2nd to work. The binding functions use typedefs within the binary_function class that you either have to define yourself, or inherit from the binary_function class.

Working code:
#include <functional>
#include <algorithm>
#include <vector>

int MyIntCounter = 0;

class MyInt : public std::binary_function<MyInt, MyInt, bool>
{
	int mId;
public:
	MyInt(): mId(++MyIntCounter) {}
	MyInt(int arg) : mId(arg){}

	bool operator()(const MyInt& rhs1 , const MyInt& rhs2) const
	{
		return rhs1.mId == rhs2.mId == mId;
	}
};

int main(int argc, char* argv[])
{
	std::vector<MyInt> ints;
	for(int i = 0; i < 10; ++i) ints.push_back( MyInt() );
	MyInt finder2(2), finder3(3);
	std::find_if( ints.begin(), ints.end(), std::bind2nd(finder2, finder3 ) );
	return 0;
}

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
ScapeCode - Blog | SlimDX






We are working on generating results for this topic
PARTNERS