Re: Member function as parameter of STL algorithm
On Jul 17, 7:42 am, many_years_after <shua...@gmail.com> wrote:
Hi, cppers:
I am studying cpp recently. As is said, member funciton can be as
one parameter of stl algorithm. BUT when I pass member function whose
parameter is instance of the class, it doesn't work. For example:
It won't work. std::sort() either needs a predicate function
(functor), or it simply needs the < (less than) operator to work
correctly.
The latter case is the easiest. Let's make your code work...
#include <iostream>
#include <ostream>
#include <algorithm>
#include <vector>
using namespace std;
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)
bool LargerThan(const Point& p) const // const is IMPORTANT
here...
{
return (x > p.x)|| ((x==p.x) && (y > p.y));
}
void print()
{
cout << x << " " << y;
}
void printWithPre(const char* s)
{
cout << s << " " << x;
}
bool operator< (const Point& p ) const
{
return !LargerThan(p);
}
};
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 WHEN COMPILING
Now that the operator is defined, simply use:
sort(vec.begin(), vec.end());
return 0;
}
I don't know why it does not work. What's the reasong?