Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

std::vector's reserve(), erase() and clear()

34 views
Skip to first unread message

Alex Vinokur

unread,
Sep 23, 2005, 5:22:51 AM9/23/05
to

====== foo.cpp ======
#include <vector>
#include <iostream>
using namespace std;

#define SHOW cout << "capacity = " << v.capacity() << "\t size = " << v.size() << endl;

int main()
{
vector<int> v;
SHOW;
v.reserve(100);
SHOW;
v.resize(100);
SHOW;
v.erase(v.end() - 1);
SHOW;
v.clear();
SHOW;

return 0;

}


=====================

1. Output for GNU g++ 3.4.4, GNU gpp 4.0.1, Bolrand C++ 5.5.1, Digital Mars 8.38n
---------------------------
capacity = 0 size = 0
capacity = 100 size = 0
capacity = 100 size = 100
capacity = 100 size = 99
capacity = 100 size = 0
---------------------------

2. Output for Microsoft C++ 13.00.9466
---------------------------
capacity = 0 size = 0
capacity = 100 size = 0
capacity = 100 size = 100
capacity = 100 size = 99
capacity = 0 size = 0
---------------------------

We can see that capacity == 0 after clear() for Microsoft C++.
Is it correct behavior?


--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn


Tom Widmer [VC++ MVP]

unread,
Sep 23, 2005, 6:11:21 AM9/23/05
to
Alex Vinokur wrote:

> 2. Output for Microsoft C++ 13.00.9466
> ---------------------------
> capacity = 0 size = 0
> capacity = 100 size = 0
> capacity = 100 size = 100
> capacity = 100 size = 99
> capacity = 0 size = 0
> ---------------------------
>
> We can see that capacity == 0 after clear() for Microsoft C++.
> Is it correct behavior?

It is debatable whether it is allowed by the standard. Dinkumware
changed the behaviour (for VC7.1) to set capacity to 0 after a clear(),
apparently based on user feedback (but ignoring the rather well known
capacity reducing swap idiom). All iterators are invalidated by a
clear(), so iterator invalidation rules aren't broken. The standard
isn't explicit about whether any operations can reduce capacity, so
overall I think it is probably conforming.

In any case, the behaviour has been changed back to be in line with the
other compilers for VC8 AFAIK.

Tom

adeb...@club-internet.fr

unread,
Sep 23, 2005, 9:36:12 AM9/23/05
to

AFAIK it's unspecified by the standard, so the implementation is free
to do whatever she wants.

Arnaud
MVP - VC

0 new messages