只是想知道尺寸函数计算代价是否昂贵?
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
}
答案 0 :(得分:7)
如果我们查看std::vector::size的cppreference条目,则说:
<强>复杂性强>
常数。
所以它会在恒定的时间内运行。这与C ++标准草案Table 96 — Container requirements
一致,后者将size()
的复杂性列为常量。