About std::vector::resize().
Carlo Wood
carlo@alinoe.com
Tue May 25 13:46:00 GMT 2004
As far as I know this is implementation dependend and using swap
would be allowed (or so I was told not long ago).
>From a practical point of view this seems a very good idea.
One could implement a resize from size m to size n (n > m) as:
- Create new vector with size n, using the default constructor
for all elements.
- Swap the first m elements.
- Destroy the old vector.
On Tue, May 25, 2004 at 12:52:26PM +0530, Dhruv Matani wrote:
> Hello,
> Consider:
>
> std::vector<std::vector<int> > vv;
>
> Now, if this vector were to be resized, then the operation would cause a
> lot of memory movement, because vector's copy ctor, and assignment
> operator would do a lot of de-allocation, and re-allocation of memory.
> However, IMHO this can be prevented by making use of the fact that the
> vector can be swapped very easily, in an exception safe manner. So,
> instead of actually copying, we may swap an empty vector with the actual
> vector to get the desired effect. This would prevent a lot of copying.
> So, when the vector grows in size during normal operation such as during
> a push_back(), even then this copying can be prevented. So, we may
> specialize the functions for the standard containers, so that whenever
> we have a std::vector<standard_container>, then the copying while
> resizing is avoided totally. However, this does not seem necessary for
> std::string, because the implementation is reference counted anyways.
>
> Same goes for:
>
> std::vector<std::list<int> > lv;
>
> And for the other containers too.
>
> The only remaining thing would be that is this permitted by the
> standard? From my partial reading of the 1996 standard, this seems OK,
> but there may be something that I overlooked.
>
> --
> -Dhruv Matani.
> http://www.geocities.com/dhruvbird/
>
> Proud to be a Vegetarian.
> http://www.vegetarianstarterkit.com/
> http://www.vegkids.com/vegkids/index.html
>
--
Carlo Wood <carlo@alinoe.com>
More information about the Libstdc++
mailing list