The code is mostly legal. Some compilers may accept it...however, writing it the following way is sure to work (assuming you have using namespace std
defined):
template <typename T>
void printlist(list<T> a)
{
typename list<T>::iterator i;
for (i=a.begin(); i!=a.end(); ++i)
cout<<*i<<" ";
}
For efficiency, you should pass in the list as a const reference:
template <typename T>
void printlist(const list<T>& a)
{
typename list<T>::const_iterator i;
for (i=a.begin(); i!=a.end(); ++i)
cout<<*i<<" ";
}
However, there is an STL algorithm that already does this for you. Assuming you want to print out a list of integers, just write:
copy( a.begin(), a.end(), ostream_iterator<int>( cout, " " ) );
Just replace int
with the appropriate element type. Note: This algorithm works on any sequence.