string :: npos是什么意思?

sap*_*sap 3 c++

以下陈述是什么意思?

    string s="Joe Alan Smith"";
    cout << (s.find("Allen") == string::npos) << endl; 
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 14

实际上string::find()返回找到的字符串的位置,但是如果找不到给定的字符串,则返回string::npos,这npos意味着没有位置.

npos是无符号整数值,标准将其定义为-1(带符号表示),表示无位置.

//npos is unsigned, that is why cast is needed to make it signed!
cout << (signed int) string::npos <<endl; 
Run Code Online (Sandbox Code Playgroud)

输出:

-1

请参阅Ideone:http://www.ideone.com/VRHUj

  • 该值不是实现定义的; 标准指定它是`string :: size_type(-1)`. (3认同)