many_years_after wrote:
Quote:
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:
>
class Point
{
public:
int x; int y;
Point(int xx, int yy)
{
x = xx;
y = yy;
}
friend ostream& operator<<(ostream& out,const Point& p)
error: ostream not declared. Yes it's easy to fix, but if you want help,
posting compilable code (or in this case, code that has no other errors)
will help.
Quote:
{
out << p.x << " "<< p.y << endl;
IMHO, you should remove the endl. There are two reasons:
1) endl provokes a flush. If the user wants a flush, the user can flush on
his/her own. 2) endl sends an '\n'. This will make this operator useless in
most cases. Try to use it to output tabular data, for instance.
Quote:
return out;
}
bool LargeThan(const Point& p)
bool LargeThan(const Point& p) const
Quote:
{
>
return (x p.x)|| ((x==p.x) && (y p.y));
}
void print()
void print() const
Quote:
{
cout << x << " " << y;
}
This does exactly what (parts of) operator<<(ostream&, const Point&) does,
and IMO what operator << should have done.
Quote:
void printWithPre(const char* s)
void printWithPre(const char* s) const
Quote:
{
cout << s << " " << x;
}
};
int main()
{
vector<Pointvec;
>
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
Here, mem_fun_ref returns a functor with
bool operator()(Point& a, const Point& b) const, and this calls
a.LargeThan(b). Not that LargeThan is non-const on a. The standard
specifies:
It is assumed that comp [the comparator] will not apply any non-constant
function through the dereferenced iterator.
On g++ 4.2.0 it compiles only if the comparator is called with two
references to const objects. Is this a bug?
Quote:
return 0;
}
>
I don't know why it does not work. What's the reasong?
If a member function doesn't modify the object, consider making it const.
--
rbh