从此代码:
#include <iostream>
#include <typeinfo>
#include <string>
int main() {
std::string const s = "Thisisastring";
std::string const ss = "Thisisastringg";
std::string const sss = "Thisisastrin";
auto p = ss.find(s);
std::cout << "p:" << typeid(p).name() << "\np =" << p << std::endl;
auto pp = sss.find(s);
std::cout << "pp:" << typeid(pp).name() << "\npp =" << pp << std::endl;
return 0;
}
我得到以下输出:
p:m
p =0
pp:m
pp =18446744073709551615
问题:
在this link中,
p
应该相对于size_type
的类型是m
吗?pp
的值是什么意思?溢出了吗? 最佳答案
size_type
本身不是类型,它是一个别名,定义如下:
typedef Allocator::size_type size_type; // until c++11
typedef std::allocator_traits<Allocator>::size_type size_type; // since c++11
由于使用的是
std::string
,因此分配器为std::allocator<char>
,因此size_type
为std::size_t
。std::type_info::name
的返回值是实现定义的,而m
是编译器(大概是g ++)选择用于std::size_t
的返回值。找不到子字符串时,
std::basic_string::find
的返回值为std::basic_string::npos
,其定义为:static const size_type npos = -1;
您的情况归结为:
static const std::size_t npos = -1;
// which is (due to arithmetic modulo 2^n):
static const std::size_t npos = std::numeric_limits<std::size_t>::max();
对于编译器,结果值为
18446744073709551615
,即2^64 - 1
,因为std::size_t
可能是计算机上的64位值。这是一个可能的值,std::size_t
不需要为64位长。您应该始终直接针对
std::basic_string::find
测试std::basic_string::npos
(和其他相关函数)的返回值。