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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With