c++ vector

If I have a vector and i iterate throw the elements :
for (i = 0; i < v.size(); ++i) , does it calculate v.size() each time and lose execution time ? im saying is it less efficent doing this than doing
int x = v.size(); for (i = 0; i < x; ++i) , because i know when using strlen function it calculates each time and loses execution time so thats why im asking.
Use ranged for.
1
2
3
for (auto &element : v){
    //...
}
> does it calculate v.size() each time and lose execution time ?

Unless the vector is immutable (const), and its size would never change, the two loops are not equivalent.

There is no real calculation involved in getting the size of a vector; it is just a look up.
On one program I was working on, there was a vector that contained a bunch of nodes. Each generation (an outer loop), more nodes were created off the existing nodes, and the new nodes were push_back'd into the same vector that was currently being worked on. If I had used vector.size() over each node, the algorithm would fail because it would keep pushing back more nodes and never reach the end. But, by saving the pre-push_back size of the vector each generation, I avoided this problem.

Point being, save the size() of the vector if you logically need to, otherwise you're just wasting effort pre-optimizing (the root of all evil).
Topic archived. No new replies allowed.