STL list <unsigned short> and ostream

Hi
I have a following class:
/////////////////Data.h
class Data {
public:
...
friend ostream& operator<< (ostream& out, const Data& rData);
...
private:
list <unsigned short> seq;
...
}

and its implementation as
/////////////////Data.cpp
....
ostream& operator<< (ostream& out, const Data& rData) {
list<unsigned short>::iterator itr;
for (itr = rData.seq.begin (); itr != rData.seq.end (); itr++) {
out << *itr;
}
return out;
}
...

I am using g++ (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7 x86_64-linux-gnu)

It gives me the following error on compile:

$>g++ testDriveriData.cpp Data.cpp
Data.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Data&)’:
Data.cpp:51: error: no match for ‘operator=’ in ‘itr = rData->Data::seq.std::list<_Tp, _Alloc>::begin [with _Tp = short unsigned int, _Alloc = std::allocator<short unsigned int>]()’
/usr/include/c++/4.2/bits/stl_list.h:113: note: candidates are: std::_List_iterator<short unsigned int>& std::_List_iterator<short unsigned int>::operator=(const std::_List_iterator<short unsigned int>&)

Any clue?
Similar code in other program works fine.

Thanks.
-sn

Last edited on
You are requesting a non-const iterator from a const reference. This doesn't work. An improved solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Data
{
  public:
    ...
    std::ostream& print(std::ostream& os) const
    { // not really inlined, just for brevity
      std::copy(seq.begin(), seq.end(), std::ostream_iterator<unsigned short>(os, " "));
      return os;
    }
    ...
};
...
std::ostream& operator<< (std::ostream& out, const Data& rData)
{
  return rData.print(out);
}

This wil print a " " between each number, can be substituted by "\n" or nothing at all if you want.
Hi exception,

It (ostream) now works.
Also changing the iterator in the original code (from iterator to the const_iterator) works.
I got that hint from your answer.

Thank you for the correct reply.

-sn
Topic archived. No new replies allowed.