Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c++ - Does std::vector.pop_back() change vector's capacity?

If I allocated an std::vector to a certain size and capacity using resize() and reserve() at the beginning of my program, is it possible that pop_back() may "break" the reserved capacity and cause reallocations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No. The only way to shrink a vector's capacity is the swap trick

template< typename T, class Allocator >
void shrink_capacity(std::vector<T,Allocator>& v)
{
   std::vector<T,Allocator>(v.begin(),v.end()).swap(v);
}

and even that isn't guaranteed to work according to the standard. (Although it's hard to imagine an implementation where it wouldn't work.)

As far as I know, the next version of the C++ standard (what used to be C++0x, but now became C++1x) will have std::vector<>::shrink_to_fit().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...