In C++, std::list::assign() replaces the whole content of a std::list. It first erases every old element, then builds new nodes for the elements you describe.
You can describe the new elements in three ways: a count and a value, a pair of iterators, or a {...} list. Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call assign on the list you already have. Pick the form that matches how your new data is stored.
C++
l.assign(4, 9); // four copies of 9
l.assign(src.begin(), src.end()); // copy from another container
l.assign({1, 2, 3}); // from a braced list
Call
What it does
l.assign(4, 9)
The list now holds four elements, all equal to 9.
l.assign(first, last)
Copies every element of the iterator range [first, last). The source can be a vector, deque, array, or another list.
l.assign({1, 2, 3})
Replaces the content with the values in the braces.
l = other; also replaces the content, but it needs a whole list. assign() also accepts counts, ranges of other containers, and braced lists.
assign({7, 8}) drops 100 200 300 and stores just two nodes, 7 and 8.
push_back(9) links a third node at the end. The first two nodes stay where they are.
front() reads 7, back() reads 9, and size() counts three elements.
Frequently Asked Questions
It erases every element that the list 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 list into another list. assign() is more flexible: it can fill from a count, from an iterator range of any container, or from a braced list.
No. All old nodes are destroyed first. If you want to keep them, use push_back(), push_front(), or insert().
No. The iterator range must come from a different container. Pointing into the same list is undefined behavior because assign() destroys the old nodes first.
Yes. std::vector::assign() has the same three forms. A list builds one new node for every element, while a vector may reuse its existing memory block.