标准C++字符串库的奇怪行为

Mar*_*čko 0 c++ string

我开始为发现子串编写程序,但它不起作用,它总是找到子串.这是奇怪的行为,所以我写了简单的程序:

#include <iostream>
#include <string>

using namespace std;

int main(){
    string str;
    str = "aaaa";
    unsigned found = str.find("bbbb");
    if(found!=std::string::npos){
        cout << "I FOUND IT!!!!\n";
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它显示文字"I FOUND IT !!!!" 我不明白发生了什么.

Mik*_*ine 6

std::string::find 返回size_t

std::string::npos被定义为适合size_t的最大值,可能0xFFFFFFFFFFFFFFFF是64位程序.

当你将它转换为unsigned int时,这可能是32位左右 0xFFFFFFFF

0xFFFFFFFFFFFFFFFF != 0xFFFFFFFF你得到你看到的结果时.