2

I've been having some problems trying to implement an overloaded << operator function that can print out a std::list which is a member of one of my classes. The class looks like this:

class NURBScurve {
  vector<double> knotVector;
  int curveOrder;
  list<Point> points;
public:
  /* some member functions */
  friend ostream& operator<< (ostream& out, const NURBScurve& curve);
};

The key member variable I am interested in is the list of "Points" - this is another class that I have created which stores coordinates of a point along with associated member functions. When I try and implement the overloaded << operator function as:

ostream& operator<<( ostream &out, const NURBScurve &curve)
{
 out << "Control points: " << endl;
 list<Point>::iterator it;
 for (it = curve.points.begin(); it != curve.points.end(); it++)
    out << *it; 
 out << endl;
 return out;
}

I start to get problems. Specifically, I get the following error: error:

no match for ‘operator=’ in ‘it = curve->NURBScurve::points. std::list<_Tp, _Alloc>::begin [with _Tp = Point, _Alloc = std::allocator<Point>]()’
/usr/include/c++/4.2.1/bits/stl_list.h:113: note: candidates are: std::_List_iterator<Point>& std::_List_iterator<Point>::operator=(const std::_List_iterator<Point>&)

I'm a bit stumped here, but I believe it has something to do with the list iterator I am using. I'm also not too confident with the notation of curve.points.begin().

If anyone can shed some light on the problem I would appreciate it. I'm at the point where I've been staring at the problem for too long!

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • You could give the [pretty printer](http://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers) a try :-) – Kerrek SB Aug 10 '11 at 16:34

2 Answers2

9

curve is const-qualified, so curve.points is const-qualified and curve.points.begin() returns a std::list<Point>::const_iterator, not a std::list<Point>::iterator.

Containers have two begin() and end() member functions: one pair are not const-qualified member functions and return iterators, the other pair are const-qualified and return const_iterators. This way you can iterate over a container that is not const and both read and modify the elements in it, but you can also iterate over a const container with read-only access.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • I don't know how you replied as fast as you did, but you are completely right, and this has fixed my problem. I suppose this has highlighted my lack of understanding of the std library, but I'll keep cracking on... Thanks! – Rob Simpson Aug 10 '11 at 16:26
6

Or,

You could use std::copy as:

std::copy(points.begin(), points.end(), 
                      std::ostream_iterator<Point>(outStream, "\n"));

Make sure the signature of operator<< is this:

std::ostream & operator <<(std::ostream &out, const Point &pt);
                                            //^^^^^ note this
Nawaz
  • 353,942
  • 115
  • 666
  • 851