Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top