In C++, std::vector::assign() replaces the whole content of a std::vector. It first removes every old element, then stores the new ones you describe.
You can describe the new elements in three ways: a count and a value, a pair of iterators, or a {...} list. Include <vector> to use it.
This is a member of std::vector<T>, a dynamic contiguous array. Elements sit in one block, so v[i] and data() are fast. Growing past capacity() reallocates and can invalidate iterators, references, and pointers. Prefer push_back / pop_back at the end; middle inserts shift elements.
Syntax
Call assign on the vector you already have. Pick the form that matches how your new data is stored.
C++
v.assign(4, 9); // four copies of 9
v.assign(src.begin(), src.end()); // copy from another container
v.assign({1, 2, 3}); // from a list
Call
What it does
v.assign(4, 9)
The vector now holds four elements, all equal to 9.
v.assign(first, last)
Copies every element from the iterator range [first, last). The source can be a vector, list, array, or another vector.
v.assign({1, 2, 3})
Replaces the content with the values in the braces.
d = other; also replaces the content, but it needs a whole vector. assign() works with ranges and lists too.
assign({"Zoe", "Max"}) replaces all three with just two names.
The loop uses const std::string&, so each name is read without making a copy.
Frequently Asked Questions
It removes every element that the vector holds and then stores new elements. The new elements come from a count and value, a pair of iterators, or an initializer list.
operator= copies a whole vector into another vector. assign() is more flexible: it can fill from a count, from any iterator range (even a vector), or from a braced list.
No. All old elements are destroyed first. If you want to keep them, use push_back() or insert().
No. The iterator range must come from a different container. Pointing into the same vector is undefined behavior because assign() destroys the old elements first.
Yes. std::vector::assign() has the same three forms. The deque version works in a similar way, but a deque stores data in several blocks while a vector uses one contiguous block.