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 body
objects wish have in bodies
.
unsigned int const numparticles = 1000;
i have populated bodies
with 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?
safety : since
.size()
not throw exceptions, safe use.size()
.readability : imho,
bodies.size()
conveys size of vectorbodies
morenumparticles
.convention : according conventions too, better use
.size()
property of vector, instead of variablenumparticles
.performance:
.size()
constant complexity member function, there no significant performance difference between usingconst int
,.size()
.
Comments
Post a Comment