[英]Dereferencing string iterator yields int
I get this error 我收到这个错误
comparison between pointer and integer ('int' and 'const char *')
For the following code 对于以下代码
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
std::string s("test string");
for(auto i = s.begin(); i != s.end(); ++i)
{
cout << ((*i) != "s") << endl;
}
}
Why does dereferencing the string iterator yield an int
and not std::string
? 为什么解除引用字符串迭代器会产生一个
int
而不是std::string
?
Actually, it does not yield an int
, it yields a char
(because a string iterator iterates over the characters in the string). 实际上,它不会产生一个
int
,它会产生一个char
(因为字符串迭代器迭代字符串中的字符)。 Since the other operand of !=
is not a char
(it's a const char[2]
), standard promotions and conversions are applied to the arguments: 由于
!=
的另一个操作数不是char
(它是一个const char[2]
),标准的促销和转换将应用于参数:
char
is promoted to int
via integral promotion char
通过整体推广升级为int
const char[2]
is converted to const char*
via array-to-pointer conversion, const char[2]
通过数组到指针转换转换为const char*
, This is how you arrive at the int
and const char*
operands the compiler is complaining about. 这是你到达编译器抱怨的
int
和const char*
操作数的方法。
You should compare the dereferenced iterator to a character, not to a string: 您应该将解除引用的迭代器与字符进行比较,而不是与字符串进行比较:
cout << ((*i) != 's') << endl;
""
encloses a string literal (type const char[N]
), ''
encloses a character literal (type char
). ""
包含一个字符串文字(类型const char[N]
), ''
包含一个字符文字( char
类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.