Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is vector.size() function computational heavy? [duplicate]

Tags:

c++

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
}
like image 737
Daniel Avatar asked Aug 29 '26 03:08

Daniel


1 Answers

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.

like image 96
Shafik Yaghmour Avatar answered Aug 31 '26 18:08

Shafik Yaghmour