I’m having a problem when trying to output STL iterator values in C++. The following code generates an error – no matter what template target I’m going to use:
template <typename T>
void outputVector(vector<T> &v)
{
typename vector<T>::const_iterator iter;
for(iter = v.begin(); iter != v.end(); iter++)
{
cout << *iter << endl;
}
The message is
no match for ‘operator<<‘ in ‘std::cout << iter.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* with _Iterator = const Node*, _Container = std::vector >’
When replacing the for loop with
for(iter = v.begin(); iter != v.end(); iter++)
{
T t = *iter;
cout << t << endl;
}
everything works just fine.
Do you have any problem what the problem might be? The used class “Node” overloads the “<<” operator by
ostream & operator<<(ostream &o, Node &n)
{
o << "Hello World" << endl;
return o;
}
Your
operator<<fails to take a reference toconstfor the second argument:This means the temporary
*itercannot bind to that argument.Get into the habit of using
constany place you don’t need to modify an object:Now, the reference argument can bind to the temporary. Huzzah!
This successful guess brought to you by the colour blue and the number 42.