Topic: Member function as parameter of STL algorithm
Author: many_years_after <shuanyu@gmail.com>
Date: Wed, 18 Jul 2007 10:40:36 CST Raw View
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?
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Author: jpalecek@web.de
Date: Thu, 19 Jul 2007 23:46:40 CST Raw View
On Jul 18, 6:40 pm, many_years_after <shua...@gmail.com> wrote:
> 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?
Your comparison function must take both parameters as const
Jiri Palecek
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]