谷动谷力

标题: C++ string::npos 㳀析 [打印本页]

作者: fannifu    时间: 2023-8-16 10:14
标题: C++ string::npos 㳀析
C++  string::npos 㳀析

1. 关于npos的定义
string::npos 是一个静态成员常量,表示 size_t 的最大值;
size_t 的详细讲解
该值表示“直到字符串结尾”,作为返回值它通常被用作表明没有匹配;
string::npos 的定义:
static const size_type npos = -1;

2. 使用方法
要想判断 find() 的结果是否为 npos,最好的办法是直接比较。比如:
if (str.find("abc") == string::npos) {
        ...
}

3. 注意事项
int index = str.find("abc");  
if (index == string::npos)  
  ...

上述代码中,index 的类型被定义为 int,这是错误的,即使定义为 unsigned int 也是错的,它必须定义为 string::size_type。

4. 证明:-1 表示 size_t 的最大值
#include <iostream>
#include <limits>
#include <string>
using namespace std;

int main()
{
    size_t npos = -1;

        // X86:npos: 4294967295
    // x64:npos: 18446744073709551615
    cout << "npos: " << npos << endl;

        // X86:size_t max: 4294967295
    // x64:size_t max : 18446744073709551615
    cout << "size_t max: " << numeric_limits<size_t>::max() << endl;

    return 0;
}
可见,它们是相等的,也就是说 npos 表示 size_t 的最大值。






欢迎光临 谷动谷力 (http://bbs.sunsili.com/) Powered by Discuz! X3.2