这句话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,因为代码更清晰.
She*_*per 47
string::npos是一个常数(可能-1)代表一个非位置.find当找不到模式时,它由方法返回.
cod*_*ict 23
该文件string::npos说:
npos是一个静态成员常量值,对于size_t类型的元素具有最大可能值.
作为返回值,它通常用于指示失败.
该常量实际上定义为值-1(对于任何特征),因为size_t是无符号整数类型,因此成为此类型的最大可表示值.
小智 16
size_t是无符号变量,因此'无符号值= - 1'自动使其成为最大可能值size_t:18446744073709551615
std::string::npos是实现定义的索引,总是超出任何std::string实例的范围.各种std::string函数返回它或接受它在字符串情况结束之后发出信号.它通常是一些无符号整数类型,其值通常std::numeric_limits<std::string::size_type>::max ()是(由于标准整数提升)通常可比较-1.
我们必须使用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)
| 归档时间: |
|
| 查看次数: |
106772 次 |
| 最近记录: |