Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL - assignment operator vs. `assign` member function

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:

  1. One wants to assign a sub-range of the vector (not from the beginning to the end).
  2. The assignment is done from an array.

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?

like image 930
Yakov Avatar asked Nov 01 '13 21:11

Yakov


1 Answers

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.

like image 146
Collin Dauphinee Avatar answered Sep 21 '22 16:09

Collin Dauphinee