Member function as parameter of STL algorithm

M

many_years_after

hi, cppers:

It is said that member function can be as parameter of STL algorithm.
BUT when I pass member function whose parameter is a instance of the
class, it dose not work.

class Point
{
public:
int x; int y;
Point(int xx, int yy)
{
x = xx;
y = yy;
}
friend ostream& operator<<(ostream& out,const Point& p)
{
out << p.x << " "<< p.y << endl;
return out;
}
bool LargeThan(const Point& p)
{

return (x > p.x)|| ((x==p.x) && (y > p.y));
}
void print()
{
cout << x << " " << y;
}
void printWithPre(const char* s)
{
cout << s << " " << x;
}
};
int main()
{
vector<Point> vec;

for (int i = 0; i < 10; i++)
vec.push_back(Point(i, i));

for_each(
vec.begin(),
vec.end(),
bind2nd(mem_fun_ref(&Point::printWithPre),"hello:")
); // OK


for_each(
vec.begin(),
vec.end(),
mem_fun_ref(&Point::print)); // OK
sort(vec.begin(), vec.end(), mem_fun_ref(&Point::LargeThan)); //
ERROR


return 0;
}

what is the reason?
 
D

dasjotre

for_each(
vec.begin(),
vec.end(),
mem_fun_ref(&Point::print)); // OK
sort(vec.begin(), vec.end(), mem_fun_ref(&Point::LargeThan)); //
ERROR

return 0;

}

what is the reason?

std::sort takes binary predicate as third argument
mem_fun_ref(&Point::LargeThan) returns unary
function that takes reference to a Point object.


regards

DS
 
J

James Kanze

std::sort takes binary predicate as third argument
mem_fun_ref(&Point::LargeThan) returns unary
function that takes reference to a Point object.

No. In this case, mem_fun_ref returns a binary functional
object that takes a reference to a reference as its second
argument. It doesn't compile because the language doesn't allow
references to references.

The function adaptors in the original standard are seriously
broken, and close to useless in practice. Boost has solutions
to this; they were adopted in TR1, and will be part of the next
version of the standard. So the "correct" answer here is to
forget about mem_fun_ref, and use the Boost stuff.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top