c++ - Using .size() vs const variable for loops -


i have vector:

vector<body*> bodies; 

and contains pointers body objects have defined.

i have unsigned int const contains number of bodyobjects wish have in bodies.

unsigned int const numparticles = 1000; 

i have populated bodieswith numparticles amount of body objects.

now if wish iterate through loop, example invoking each of body's update() functions in bodies, have 2 choices on can do:

first:

for (unsigned int = 0; < numparticles; i++) {     bodies.at(i)->update(); } 

or second:

for (unsigned int = 0; < bodies.size(); i++) {     bodies.at(i)->update(); } 

there pro's , con's of each. know 1 (if either) better practice, in terms of safety, readability , convention.

i suggest use .size() function instead of defining new constant.

why?

  1. safety : since .size() not throw exceptions, safe use .size().

  2. readability : imho, bodies.size() conveys size of vector bodies more numparticles.

  3. convention : according conventions too, better use .size() property of vector, instead of variable numparticles.

  4. performance: .size() constant complexity member function, there no significant performance difference between using const int , .size().


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -