简体   繁体   English

size_t数据类型是否可以安全地用于str.find()?

[英]Is the size_t data type safe to use for str.find()?

I've been looking at code for the find() function for strings, and they store the result of that in a variable with data type size_t. 我一直在查看字符串的find()函数的代码,并将它的结果存储在数据类型为size_t的变量中。 However it is my understanding that size_t is an unsigned int, and if find() does not find the intended string, it returns -1. 但是我的理解是size_t是unsigned int,如果find()找不到想要的字符串,则返回-1。 For example if I have 例如,如果我有

string s = "asdf";
size_t i = s.find("g")
cout << i;

It gives me 4294967295. However if I replace size_t with the int data type, it gives me -1. 它给了我4294967295.但是如果我用int数据类型替换size_t,它给我-1。 The strange thing is when I make a comparison like 奇怪的是,当我进行比较时

string s = "asdf";
size_t i = s.find("g")
if (i == -1) { do_something; }

it works whether i is size_t or int. 无论我是size_t还是int,它都可以工作。 So which do I use? 那么我用哪个? int or size_t? int还是size_t?

Neither. 都不是。

Under the std::string::find documentation , it recommends that you use string::size_type and string::npos to detect not found in find : std::string::find文档下 ,它建议你使用string::size_typestring::npos来检测findfind

 std::string::size_type i = s.find("g");
 if (i == std::string::npos) std::cout << "Not Found\n";

Live example. 实例。

It shouldn't be surprising that int and size_t can be compared with -1 and work, they will have the bits, so when cast to do the comparison they will compare equally, you should however receive a warning such as: 毫无size_t intsize_t可以与-1进行比较并且工作,它们将具有位,因此当进行比较时,它们将进行相同的比较,但是您应该收到警告,例如:

warning: comparison between signed and unsigned integer expressions [-Wsign-compare] 警告:有符号和无符号整数表达式之间的比较[-Wsign-compare]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM