我只是想知道我是否应该使用std::size_t for循环之类的东西,而不是int? 例如:
#include <cstdint>
int main()
{
for (std::size_t i = 0; i < 10; ++i) {
// std::size_t OK here? Or should I use, say, unsigned int instead?
}
}
一般来说,关于何时使用std::size_t的最佳实践是什么?
我只是想知道我是否应该使用std::size_t for循环之类的东西,而不是int? 例如:
#include <cstdint>
int main()
{
for (std::size_t i = 0; i < 10; ++i) {
// std::size_t OK here? Or should I use, say, unsigned int instead?
}
}
一般来说,关于何时使用std::size_t的最佳实践是什么?
当前回答
Size_t是一个无符号整型,它可以表示系统中最大的整数。 只有当你需要非常大的数组,矩阵等。
有些函数返回size_t,如果你试图进行比较,编译器会警告你。
通过使用适当的有符号/无符号数据类型或简单的类型转换来避免快速破解。
其他回答
当使用size_t时,注意下面的表达式
size_t i = containner.find("mytoken");
size_t x = 99;
if (i-x>-1 && i+x < containner.size()) {
cout << containner[i-x] << " " << containner[i+x] << endl;
}
不管x的值是多少,if表达式都会得到false。 我花了几天时间才意识到这一点(代码太简单了,我没有做单元测试),尽管只花了几分钟就找到了问题的根源。不确定是执行强制转换还是使用零更好。
if ((int)(i-x) > -1 or (i-x) >= 0)
两种方法都有效。这是我的测试
size_t i = 5;
cerr << "i-7=" << i-7 << " (int)(i-7)=" << (int)(i-7) << endl;
输出:i-7=18446744073709551614 (int)(i-7)=-2
我想听听其他人的意见。
很快,大多数计算机将是64位体系结构,带有64位操作系统,运行在数十亿个元素的容器上的程序。然后必须使用size_t而不是int作为循环索引,否则在32位和64位系统上,索引将在2^32:th元素处换行。
为未来做好准备!
我一直在努力理解什么时候使用它。但size_t只是一个无符号整型数据类型,它定义在各种头文件中,如<stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h>等。
It is used to represent the size of objects in bytes hence it's used as the return type by the sizeof operator. The maximum permissible size is dependent on the compiler; if the compiler is 32 bit then it is simply a typedef (alias) for unsigned int but if the compiler is 64 bit then it would be a typedef for unsigned long long. The size_t data type is never negative(excluding ssize_t) Therefore many C library functions like malloc, memcpy and strlen declare their arguments and return type as size_t.
/ Declaration of various standard library functions.
// Here argument of 'n' refers to maximum blocks that can be
// allocated which is guaranteed to be non-negative.
void *malloc(size_t n);
// While copying 'n' bytes from 's2' to 's1'
// n must be non-negative integer.
void *memcpy(void *s1, void const *s2, size_t n);
// the size of any string or `std::vector<char> st;` will always be at least 0.
size_t strlen(char const *s);
Size_t或任何无符号类型可能被视为循环变量,因为循环变量通常大于或等于0。
Size_t是一种非常易读的方式来指定项的大小维度——字符串的长度,指针占用的字节数,等等。 它也可以跨平台移植——你会发现64位和32位都可以很好地使用系统函数和size_t——这是unsigned int可能做不到的(例如,什么时候应该使用unsigned long
Size_t是sizeof操作符的结果类型。
size_t用于对数组的大小或索引进行建模的变量。Size_t传达语义:您立即知道它表示字节或索引的大小,而不仅仅是另一个整数。
此外,使用size_t表示字节大小有助于使代码可移植。