Sign in to follow this  

std::vector clear zeroing capacity

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by deathkrush
I 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.

[edit] 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.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this