何时使用std :: size_t? [英] When to use std::size_t?

查看:126
本文介绍了何时使用std :: size_t?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道我应该将std::size_t用于循环和填充而不是int吗? 例如:

I'm just wondering should I use std::size_t for loops and stuff instead of int? For instance:

#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的最佳做法是什么?

In general, what is the best practice regarding when to use std::size_t?

推荐答案

一个好的经验法则是,您需要在循环条件下将其与自然为std::size_t的事物进行比较的任何事物.

A good rule of thumb is for anything that you need to compare in the loop condition against something that is naturally a std::size_t itself.

std::size_t是任何sizeof表达式的类型,并且保证能够表达C ++中任何对象(包括任何数组)的最大大小.通过扩展,它也保证对任何数组索引都足够大,因此它是在数组上逐个索引进行循环的自然类型.

std::size_t is the type of any sizeof expression and as is guaranteed to be able to express the maximum size of any object (including any array) in C++. By extension it is also guaranteed to be big enough for any array index so it is a natural type for a loop by index over an array.

如果您只计算一个数字,那么使用保存该数字的变量类型或intunsigned int(如果足够大)可能会更自然,因为这些应该是自然的机器的大小.

If you are just counting up to a number then it may be more natural to use either the type of the variable that holds that number or an int or unsigned int (if large enough) as these should be a natural size for the machine.

这篇关于何时使用std :: size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆