# std::vector clear zeroing capacity

This topic is 4419 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi All, Have searched this, with no luck. I was under the impression that, having filled my vector with objects, i could .clear() it and the underlying capacity should not be changed? I have searched some online vector resources, and almost all of them report that .clear() simply calls .erase(begin(), end()), however, I have done a test and this is not the case. Is my version of the STL (default that is installed with vc7.1) not conforming, or is this expected behaviour? Alex The test I performed is below

std::vector<int> testVector;

int iCapacity = testVector.capacity(); //returns 0

testVector.push_back(5);

iCapacity = testVector.capacity(); //returns 1

testVector.resize(10);

iCapacity = testVector.capacity(); //returns 10

testVector.pop_back();

iCapacity = testVector.capacity(); //returns 10

testVector.erase(testVector.begin(), testVector.end());

iCapacity = testVector.capacity(); //returns 10

testVector.resize(10);

iCapacity = testVector.capacity(); //returns 10

testVector.clear();

iCapacity = testVector.capacity(); //RETURNS 0!!!!!



##### Share on other sites
Yep, pain in the ass, huh? :)

The secret is calling resize(0) instead.

##### Share on other sites
Thanks for the info.

Any idea whether this is the correct behaviour, or is my implementation of the STL buggy?

Nice game by the way.

Alex

##### Share on other sites
I don't know if it's wrong, but it isn't something I would have expected.

libstdc++ and stlport both give me 10 if you wanted something to compare with it to.

##### Share on other sites
I get the same behaviour with Visual Studio .NET 2003.

##### Share on other sites
Quote:
 Original post by deathkrushI get the same behaviour with Visual Studio .NET 2003.

Indeed you do, since that is 7.1.

In VC2005, however, the last call to vector::capacity() returns 10 (which is what I and I am sure many would expect), so it must be something with previous implementations. The standard draft of 1998 (and the working draft of 2005) makes no mention (as far as I can tell) regarding capacity after a call to clear(), the only requirements being that it is equivalent to erase( begin(), end() ) and post size() == 0, so capacity could be 0, I guess.

 For those who are interested, I believe the correct way to ensure a capacity of 0 is the empty-temporary/swap idiom:
std::vector< int > v;
// ...
std::vector< int >().swap( v );

jfl.

1. 1
Rutin
24
2. 2
3. 3
JoeJ
18
4. 4
5. 5

• 38
• 23
• 13
• 13
• 17
• ### Forum Statistics

• Total Topics
631706
• Total Posts
3001835
×