views:

46

answers:

1

I ran into this question today and thought I should post it for the community's reference and/or opinions.

The standard C++ containers vector, deque, list, and string provide an assign member function. There are two versions; I'm primarily interested in the one accepting an iterator range. The Josuttis book is a little ambiguous with its description. From p. 237...

Assigns all elements of the range [beg,end); this is, is replaces all existing elements with copies of the elements of [beg,end).

It doesn't say what happens if the size of the assignee container is different from the range being assigned. Does it truncate? Does it automagically expand? Is it undefined behavior?

+3  A: 

Here's what I found. It turns out I didn't have to worry about silently doing the wrong thing. Once again, the standard has the answer. From section 23.2.6.1:

void assign(Iter first, Iter last);

Effects:

erase(begin(), end());

insert(begin(), first, last);

So it's really just a shortcut for a clear() followed by an insert of the full range.

Kristo
Was just typing it up. :) To make it clearer, `assign` might have been called "`reassign`", to make it clear the contents of the container are being completely reassigned.
GMan