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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With