[英]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 我有一个问题,示例代码将在代码块环境中编译并运行,但无法在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. 当我将字符串列表更改为整数列表时,代码将在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. 对格式表示抱歉,但我无法接受它。
Add the following include directive: 添加以下include指令:
#include <string>
as that is where operator<<(std::ostream&, std::string&)
is defined. 因为那是定义了operator<<(std::ostream&, std::string&)
的地方。
Note VS2012 supports the range-based for statement , which would transform the outputting loop to: 注意VS2012支持基于范围的for语句 ,它将输出循环转换为:
for (auto const& name: names) std::cout << name << std::endl;
The ostream operator<<(ostream& os, const string& str)
is defined in the string
header. ostream operator<<(ostream& os, const string& str)
在string
标题中定义。
You probably just forgot to include it to have this kind of error. 您可能只是忘了包含它以产生这种错误。
You should just include it at the top of your file : 您应该只将其包括在文件的顶部:
#include <string>
Live example . 现场例子 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.