115

std::string::npos以下代码片段中的短语是什么意思?

found = str.find(str2);

if (found != std::string::npos)
    std::cout << "first 'needle' found at: " << int(found) << std::endl;
4

12 回答 12

122

这意味着没有找到。

它通常是这样定义的:

static const size_t npos = -1;

最好与 npos 而不是 -1 进行比较,因为代码更清晰。

于 2010-09-30T05:15:55.303 回答
61

string::npos-1是一个表示非位置的常数(可能)。find未找到模式时由方法返回。

于 2010-09-30T05:18:04.790 回答
26

的文件string::npos说:

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

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

这个常量实际上是用值 -1 定义的(对于任何特征),因为 size_t 是无符号整数类型,所以它成为这种类型的最大可能表示值。

于 2010-09-30T05:26:14.440 回答
21

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

于 2013-10-20T22:36:56.793 回答
11

std::string::npos是实现定义的索引,始终超出任何std::string实例的范围。各种std::string函数返回它或接受它以发出超出字符串结尾的信号。它通常是一些无符号整数类型,它的值通常std::numeric_limits<std::string::size_type>::max ()是(感谢标准整数提升)通常与-1.

于 2010-09-30T05:21:56.133 回答
5

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

于 2010-09-30T05:15:59.720 回答
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

如果 idx 具有值-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
...
}

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

if (s.find("hi") == std::string::npos) {
...
}

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

const int NPOS = -1;

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

if (idx == NPOS) { // works almost always
...
}
于 2015-03-18T07:43:07.950 回答
1
$21.4 - "static const size_type npos = -1;"

它由指示错误/未找到等的字符串函数返回。

于 2010-09-30T05:27:14.807 回答
1

对于这些天的 C++17 的答案,当我们有std::optional

如果你眯着眼睛假装std::string::find()返回一个std::optional<std::string::size_type>(它应该......) - 那么条件变成:

auto position = str.find(str2);

if ( position.has_value() ) {
    std::cout << "first 'needle' found at: " << found.value() << std::endl;
}
于 2020-02-02T23:09:51.773 回答
1

string::npos 的值为 18446744073709551615。如果没有找到字符串,则返回该值。

于 2020-04-20T17:01:15.873 回答
0

静态常量 size_t npos = -1;

size_t 的最大值

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

此值在用作字符串成员函数中的 len(或 sublen)参数的值时,表示“直到字符串的结尾”。

作为返回值,它通常用于表示不匹配。

此常量定义为值 -1,因为 size_t 是无符号整数类型,所以它是该类型的最大可能表示值。

于 2019-07-30T04:53:07.970 回答
0

正如其他人所提到的,string::npos 它是 size_t 的最大值

这是它的定义:

static constexpr auto npos{static_cast<size_type>(-1)};

困惑的是,错误的答案得到了投票。

这是一个快速测试示例:

int main()
{
    string s = "C   :";
    size_t i = s.rfind('?');
    size_t b = size_t (-1);
    size_t c = (size_t) -1;
    cout<< i <<" == " << b << " == " << string::npos << " == " << c;

    return 0;
}

输出:

18446744073709551615 == 18446744073709551615 == 18446744073709551615 == 18446744073709551615

...Program finished with exit code 0
于 2021-10-08T01:18:36.280 回答