Reputation: 2726
Just want to know is the size function computational costly or not?
vector<someBigType> vec;
vec.push_back(something0);
for(unsigned i = 0; i < a bigNumber; ++i)
{
// do something ...
// measure the size
int size1 = vec.size();
// A lot of push_backs (vec may grow very large)
vec.push_back(something);
// Or shall I just use counter++, whenever a push_back is called?
// measure the size again
int size2 = vec.size();
int delta = size2-size1;
// Use delta to do something
}
Upvotes: 6
Views: 12560
Reputation: 158629
If we check out cppreference entry for std::vector::size it says:
Complexity
Constant.
So it runs in constant time. Which is consistent with the draft C++ standard Table 96 — Container requirements
which lists the complexity of size()
as constant.
Upvotes: 16