Wednesday, 21 August 2013

Dereferencing string iterator won't compile

Dereferencing string iterator won't compile

I have a problem where example code will compile and run in the Code
Blocks environment but will not compile in visual studio 2012
list<string> names;
names.push_back("Mary");
names.push_back("Zach");
names.push_back("Elizabeth");
list<string>::iterator iter = names.begin();
while (iter != names.end()) {
cout << *iter << endl; // This dereference causes compile error C2679
++iter;
}
Results in the following compiler error
1>chapter_a0602.cpp(20): error C2679: binary '<<' : no operator found
which takes a
right-hand operand of type 'std::basic_string<_Elem,_Traits,_Alloc>' (or
there is no
acceptable conversion)
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Alloc=std::allocator<char>
1> ]
when I change the list of strings to a list of ints the code compiles and
runs in VS2012.
when I also change the dereference to the following it compiles
cout << *the_iter->c_str() << endl;
However I have two other dereference problems further down the code
cout << "first item: " << names.front() << endl;
cout << "last item: " << names.back() << endl;
I really don't understand why these errors are compiler dependant.
sorry about the formatting but I couldn't get it to accept the code.

No comments:

Post a Comment