This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: About std::vector::resize().
On Tue, 2004-05-25 at 18:32, Carlo Wood wrote:
> As far as I know this is implementation dependend and using swap
> would be allowed (or so I was told not long ago).
How long ago, and where? Was this issue discussed somewhere else?
Ok, fine! I was confused about whether the standard allowed it or not.
>
> >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.
Yes, exactly what I was thinking. Thanks for putting it in an algorithm
form ;-)
(From other posts: Yes, I assume that the capacity is not big enough for
the new size. If it was, then the algorithm will just get more
complicated because of the checks, but the idea remains the same).
>
> 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