string :: npos是什么意思

boo*_*oom 79 c++

这句话string::npos在这里意味着什么

found=str.find(str2);

if (found!=string::npos)
    cout << "first 'needle' found at: " << int(found) << endl;
Run Code Online (Sandbox Code Playgroud)

Bri*_*ndy 88

这意味着找不到.

它通常定义如下:

static const size_t npos = -1;
Run Code Online (Sandbox Code Playgroud)

最好比较npos而不是-1,因为代码更清晰.

  • 比较== -1可能也会让一些人认为他们可以将其转换为<0,这不是同一件事,也不会起作用. (3认同)

She*_*per 47

string::npos是一个常数(可能-1)代表一个非位置.find当找不到模式时,它由方法返回.

  • 实际显示npos = no-pos派生的+1,使其易于记忆.很明显,一旦你知道它就不会想到它,但对于第一次看到这些字母的人来说,它可能不会点击......? (14认同)
  • 在47个级别上是错误的... npos的大小为size_t,这意味着它不能为负。真正的含义是max_index,对于18位7446-744073709551615(64位size_t (2认同)

cod*_*ict 23

该文件string::npos说:

npos是一个静态成员常量值,对于size_t类型的元素具有最大可能值.

作为返回值,它通常用于指示失败.

该常量实际上定义为值-1(对于任何特征),因为size_t是无符号整数类型,因此成为此类型的最大可表示值.


小智 16

size_t是无符号变量,因此'无符号值= - 1'自动使其成为最大可能值size_t:18446744073709551615

  • size_t 对于 32 位编译器来说是 unsigned int ;unsigned long long int 用于 64 位编译器。将其设置为 -1 使其具有该无符号类型的最大 val。 (2认同)

wil*_*ilx 8

std::string::npos是实现定义的索引,总是超出任何std::string实例的范围.各种std::string函数返回它或接受它在字符串情况结束之后发出信号.它通常是一些无符号整数类型,其值通常std::numeric_limits<std::string::size_type>::max ()是(由于标准整数提升)通常可比较-1.


Rag*_*ram 5

foundnpos在无法在搜索字符串中找到子字符串的情况下。


Deb*_*ish 5

我们必须使用string::size_typefind 函数的返回类型,否则与 的比较string::npos可能不起作用。 size_type由字符串的分配器定义,必须是unsigned 整数类型。默认分配器 allocator 使用 type size_tas size_type。因为-1转换为无符号整数类型,npos 是其类型的最大无符号值。但是,确切的值取决于 type 的确切定义size_type。不幸的是,这些最大值不同。实际上,如果类型的大小(unsigned long)-1不同,则与(unsigned short)-1 不同。因此,比较

idx == std::string::npos
Run Code Online (Sandbox Code Playgroud)

如果 idx 具有 value-1和 idx 并且string::npos具有不同的类型,则可能会产生 false :

std::string s;
...
int idx = s.find("not found"); // assume it returns npos
if (idx == std::string::npos) { // ERROR: comparison might not work
...
}
Run Code Online (Sandbox Code Playgroud)

避免此错误的一种方法是直接检查搜索是否失败:

if (s.find("hi") == std::string::npos) {
...
}
Run Code Online (Sandbox Code Playgroud)

但是,通常您需要匹配字符位置的索引。因此,另一个简单的解决方案是为 npos 定义您自己的有符号值:

const int NPOS = -1;
Run Code Online (Sandbox Code Playgroud)

现在比较看起来有点不同,甚至更方便:

if (idx == NPOS) { // works almost always
...
}
Run Code Online (Sandbox Code Playgroud)