简体   繁体   English

从size_t转换为int,或者用size_t迭代?

[英]Cast from size_t to int, or iterate with size_t?

Is it better to cast the iterator condition right operand from size_t to int , or iterate potentially past the maximum value of int ? 将iterator条件右操作数从size_tint ,或者迭代可能超过int的最大值是否更好? Is the answer implementation specific? 答案实施是否具体?

int a;
for (size_t i = 0; i < vect.size(); i++)
{
    if (some_func((int)i))
    {
        a = (int)i;
    }
}

int a;
for (int i = 0; i < (int)vect.size(); i++)
{
    if (some_func(i))
    {
        a = i;
    }
}

I almost always use the first variation, because I find that about 80% of the time, I discover that some_func should probably also take a size_t. 我几乎总是使用第一个变体,因为我发现大约80%的时间,我发现some_func应该也可能采用size_t。

If in fact some_func takes a signed int, you need to be aware of what happens when vect gets bigger than INT_MAX . 如果实际上some_func采用了signed int,那么你需要知道当vect大于INT_MAX时会发生什么。 If the solution isn't obvious in your situation (it usually isn't), you can at least replace some_func((int)i) with some_func(numeric_cast<int>(i)) (see Boost.org for one implementation of numeric_cast). 如果解决方案在你的情况下并不明显(通常不是),你至少可以用some_func(numeric_cast<int>(i))替换some_func((int)i) some_func(numeric_cast<int>(i)) (参见Boost.org的一个实现) numeric_cast)。 This has the virtue of throwing an exception when vect grows bigger than you've planned on, rather than silently wrapping around to negative values. 当vect比你计划的更大时,它具有抛出异常的优点,而不是默默地回绕到负值。

I'd just leave it as a size_t , since there's not a good reason not to do so. 我只是将它size_t ,因为没有充分的理由不这样做。 What do you mean by "or iterate potentially up to the maximum value of type_t"? 你是什​​么意思“或者可能迭代到type_t的最大值”? You're only iterating up to the value of vect.size() . 你只是迭代到vect.size()的值。

For most compilers, it won't make any difference. 对于大多数编译器来说,它不会有任何区别。 On 32 bit systems, it's obvious, but even on 64 bit systems, both variables will probably be stored in a 64-bit register and pushed on the stack as a 64-bit value. 在32位系统上,显而易见,但即使在64位系统上,这两个变量也可能存储在64位寄存器中,并作为64位值在堆栈上推送。

If the compiler stores int values as 32 bit values on the stack, the first function should be more efficient in terms of CPU-cycles. 如果编译器将int值存储为堆栈上的32位值,则第一个函数在CPU周期方面应该更有效。

But the difference is negligible (although the second function "looks" cleaner) 但差异可以忽略不计(虽然第二个功能“看起来”更清洁)

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

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