Direct answer:
We can use the public member function std::vector::operator=
of the container std::vector
for assigning values from a vector to another.
- Use a constructor function
Besides, a constructor function also makes sense. A constructor function with another vector as parameter(e.g. x
) constructs a container with a copy of each of the elements in x
, in the same order.
Caution:
- Do not use
std::vector::swap
std::vector::swap
is not copying a vector to another, it is actually swapping elements of two vectors, just as its name suggests. In other words, the source vector to copy from is modified after std::vector::swap
is called, which is probably not what you are expected.
If the elements in the source vector are pointers to other data, then a deep copy is wanted sometimes.
According to wikipedia:
A deep copy, meaning that fields are dereferenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B.
Actually, there is no currently a built-in way in C++ to do a deep copy. All of the ways mentioned above are shallow. If a deep copy is necessary, you can traverse a vector and make copy of the references manually. Alternatively, an iterator can be considered for traversing. Discussion on iterator is beyond this question.
References
The page of std::vector on cplusplus.com