简体   繁体   English

vector.size()函数的计算量很大吗?

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

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: 如果我们检查cppreference条目中的std :: vector :: size内容,它会说:

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. 这与C ++标准草案Table 96 — Container requirements一致,该Table 96 — Container requirementssize()的复杂性列为常数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM