我只是想知道我是否应该使用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是sizeof操作符的结果。创建Size_t是为了引用大小。
你做某事的次数(在你的例子中是10次)与大小无关,那么为什么要使用size_t呢?Int,或者unsigned Int,应该是可以的。
当然,你在循环中对i做什么也是相关的。例如,如果将它传递给一个接受无符号整型的函数,则选择无符号整型。
在任何情况下,我都建议避免隐式类型转换。使所有类型转换显式。
其他回答
Size_t是sizeof操作符的结果类型。
size_t用于对数组的大小或索引进行建模的变量。Size_t传达语义:您立即知道它表示字节或索引的大小,而不仅仅是另一个整数。
此外,使用size_t表示字节大小有助于使代码可移植。
通常最好不要在循环中使用size_t。例如,
vector<int> a = {1,2,3,4};
for (size_t i=0; i<a.size(); i++) {
std::cout << a[i] << std::endl;
}
size_t n = a.size();
for (size_t i=n-1; i>=0; i--) {
std::cout << a[i] << std::endl;
}
第一个循环就可以了。但是对于第二个循环: 当i=0时,i——的结果将是ULLONG_MAX(假设size_t = unsigned long long),这不是你在循环中想要的结果。 此外,如果a是空的,那么n=0和n-1=ULLONG_MAX,这也是不好的。
使用std::size_t对c风格数组进行索引/计数。
对于STL容器,你会有(例如)vector<int>::size_type,它应该用于索引和计数vector元素。
实际上,它们通常都是无符号整型,但这并不能保证,特别是在使用自定义分配器时。
Size_t是一个无符号整型,它可以表示系统中最大的整数。 只有当你需要非常大的数组,矩阵等。
有些函数返回size_t,如果你试图进行比较,编译器会警告你。
通过使用适当的有符号/无符号数据类型或简单的类型转换来避免快速破解。
我一直在努力理解什么时候使用它。但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。