Reputation: 10153
vector
(as well as list
and other containers) has a member function (MF) assign
.
I want to compare the assign
MF (range version) vs. the assignment operator.
As far as I understand it is useful to use assign
when:
In other cases there are no cons to the assign
MF and the assignment operator could be used.
Am I right?
Are there some other reasons for using assign
MF?
Upvotes: 15
Views: 3407
Reputation: 13993
The main reason for using assign
is to copy data from one type of container to another.
For example, if you want to migrate the contents of an std::set<int>
to an std::vector<int>
, you can't use the assignment operator, but you can use vector.assign(set.begin(), set.end())
.
Another example would be copying the contents of two containers holding different types that are convertible to one or the other; If you try to assign std::vector<Derived*>
to an std::vector<Base*>
, the assignment operator is insufficient.
Upvotes: 18