简体   繁体   中英

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. Your compiler may warn you about the comparison i < vect.size() which involves variables of different signedness.
    If you really want i to be an int (there may be no reasons for it to be unsigned) you can use the following

    for ( int i = 0, v_size = vect.size(); i < v_size; ++i ) { /*... */ } 
  • Do you really need i at all? 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.

1) See eg this talk by 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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