简体   繁体   English

调用 vector.size() 的更有效方式

[英]More efficient way to call vector.size()

Given a vector of ints I saw my professor writing:给定一个整数向量,我看到我的教授在写:

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

I argue that his code isn't efficient and could be replaced by the following, am I right?我认为他的代码效率不高,可以用以下代码代替,对吗?

int vect_size=vect.size();
for (int i=0;i<vect_size;++i)
{
}

Don't fall into premature optimization traps like this.不要陷入这样的过早优化陷阱。 Your compiler is more than capable of optimize those lines if needed (and if instructed).如果需要(如果有指示),您的编译器完全能够优化这些行。

There are other things that you should note.您还应该注意其他事项。

  • Assuming that vect is a vector , std::vector::size() returns a size_t value, which is an unsigned type.假设vect是一个vectorstd::vector::size()返回一个size_t值,它是一个无符号类型。 Your compiler may warn you about the comparison i < vect.size() which involves variables of different signedness.您的编译器可能会警告您有关i < vect.size()的比较,其中涉及不同符号的变量。
    If you really want i to be an int (there may be no reasons for it to be unsigned) you can use the following如果您真的希望i成为int (可能没有理由将其无符号),您可以使用以下内容

    for ( int i = 0, v_size = vect.size(); i < v_size; ++i ) { /*... */ } for (int i = 0, v_size = vect.size(); i < v_size; ++i ) { /*... */ }
  • Do you really need i at all?你真的需要i吗? Since C++11 you can write range-based for loops and, in general, you may want (1) to use one of the algorithms provided by the Standard Library instead of a raw loop.由于 C++11 您可以编写基于范围的 for循环,并且通常,您可能希望(1)使用标准库提供的算法之一,而不是原始循环。

1) See eg this talk by Sean Parent. 1) 参见例如 Sean Parent 的这个演讲

You can do this:你可以这样做:

for (std::size_t i = 0, vect_size = vect.size(); i < vect_size; ++i)
{
}

This way, you can limit the scope of vect_size .这样,您可以限制 vect_size 的vect_size

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

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