std::string::npos
以下代码片段中的短语是什么意思?
found = str.find(str2);
if (found != std::string::npos)
std::cout << "first 'needle' found at: " << int(found) << std::endl;
std::string::npos
以下代码片段中的短语是什么意思?
found = str.find(str2);
if (found != std::string::npos)
std::cout << "first 'needle' found at: " << int(found) << std::endl;
这意味着没有找到。
它通常是这样定义的:
static const size_t npos = -1;
最好与 npos 而不是 -1 进行比较,因为代码更清晰。
string::npos
-1
是一个表示非位置的常数(可能)。find
未找到模式时由方法返回。
的文件string::npos
说:
npos 是一个静态成员常量值,对于 size_t 类型的元素具有最大可能值。
作为返回值,它通常用于指示失败。
这个常量实际上是用值 -1 定义的(对于任何特征),因为 size_t 是无符号整数类型,所以它成为这种类型的最大可能表示值。
size_t
是一个无符号变量,因此“无符号值 = - 1”自动使其成为可能的最大值size_t
:18446744073709551615
std::string::npos
是实现定义的索引,始终超出任何std::string
实例的范围。各种std::string
函数返回它或接受它以发出超出字符串结尾的信号。它通常是一些无符号整数类型,它的值通常std::numeric_limits<std::string::size_type>::max ()
是(感谢标准整数提升)通常与-1
.
found
将npos
在未能在搜索字符串中找到子字符串的情况下。
我们必须使用string::size_type
find 函数的返回类型,否则比较string::npos
可能不起作用。
size_type
,由字符串的分配器定义,必须是unsigned
整数类型。默认分配器 allocator 使用 type size_t
as 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
...
}
$21.4 - "static const size_type npos = -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;
}
string::npos 的值为 18446744073709551615。如果没有找到字符串,则返回该值。
静态常量 size_t npos = -1;
size_t 的最大值
npos 是一个静态成员常量值,对于 size_t 类型的元素具有最大可能值。
此值在用作字符串成员函数中的 len(或 sublen)参数的值时,表示“直到字符串的结尾”。
作为返回值,它通常用于表示不匹配。
此常量定义为值 -1,因为 size_t 是无符号整数类型,所以它是该类型的最大可能表示值。
正如其他人所提到的,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