Problem with list<T>::iterator

G

Gaijinco

This code doesn´t compile:

template <typename T>
ostream& operator<<(ostream& out, const list<T>& l) {

list<T>::iterator it = l.begin();
while(it != (l.end() - 1)) {
out << *it << " ";
++it;
}
if(l.size() > 0) {
out << *it;
}

return out;
}

My compiler says: "expected ';' before it"

Why I'm doing wrong?

Thanks.
 
R

rishabh

This code doesn´t compile:

template <typename T>
ostream& operator<<(ostream& out, const list<T>& l) {

   list<T>::iterator it = l.begin();
   while(it != (l.end() - 1)) {
      out << *it << " ";
      ++it;
   }
   if(l.size() > 0) {
      out << *it;
   }

   return out;

}

My compiler says: "expected ';' before it"

Why I'm doing wrong?

Thanks.

Please include #include <list>
 
P

peter koch

This code doesn´t compile:

template <typename T>
ostream& operator<<(ostream& out, const list<T>& l) {

   list<T>::iterator it = l.begin();
You need a typename here: typename list<T>:......

Since this is templated code, you need to tell the compiler that
iterator is a type.
   while(it != (l.end() - 1)) {
And this will not compile - list iterators are not random.
      out << *it << " ";
      ++it;
   }
   if(l.size() > 0) {
      out << *it;
   }

   return out;

}

/Peter
 
P

Peter Remmers

peter said:
And this will not compile - list iterators are not random.

And even if they were, the condition assumes that the list contains at
least one element, and fails if the list is empty (probably leads to the
condition never becoming true, at best).

/Peter
 
P

peter koch

And even if they were, the condition assumes that the list contains at
least one element, and fails if the list is empty (probably leads to the
condition never becoming true, at best).

Yes - that is true as well - I focused on the syntax errors. The
entire design could be argued. While I might have a function like the
above for convenience, my central algorithm would be based on a pair
of iterators.

/Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top