取消引用字符串迭代器会产生int

lo *_*cre 6 c++ string iterator dereference

我收到这个错误

comparison between pointer and integer ('int' and 'const char *')
Run Code Online (Sandbox Code Playgroud)

对于以下代码

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么解引用字符串迭代器会产生一个int而不是std::string

Rei*_*ica 9

实际上,它不会产生一个int,它产生一个char(因为字符串迭代器迭代字符串中的字符).由于其他操作数!=不是char(它是a const char[2]),标准促销和转换将应用于参数:

  • char晋升为int通过积分的推广
  • const char[2]转换为const char*通过数组到指针的转换,

这是你如何在到达intconst char*编译器抱怨操作数.

您应该将解除引用的迭代器与字符进行比较,而不是与字符串进行比较:

cout << ((*i) != 's') << endl;
Run Code Online (Sandbox Code Playgroud)

""包含一个字符串文字(类型const char[N]),''包含一个字符文字(类型char).