In C++, std::deque::assign() replaces the whole content of a std::deque. 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 <deque> to use it.
This is a member of std::deque<T>, a double-ended queue. A deque is fast at adding and removing at both ends, and it allows access by index like std::vector. Unlike a vector, its elements are stored in several blocks, not in one contiguous block.
Syntax
Call assign on the deque you already have. Pick the form that matches how your new data is stored.
C++
d.assign(4, 9); // four copies of 9
d.assign(src.begin(), src.end()); // copy from another container
d.assign({1, 2, 3}); // from a list
Call
What it does
d.assign(4, 9)
The deque now holds four elements, all equal to 9.
d.assign(first, last)
Copies every element from the iterator range [first, last). The source can be a vector, list, array, or another deque.
d.assign({1, 2, 3})
Replaces the content with the values in the braces.
d = other; also replaces the content, but it needs a whole deque. 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 deque 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 deque into another deque. 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(), push_front(), or insert().
No. The iterator range must come from a different container. Pointing into the same deque is undefined behavior because assign() destroys the old elements first.
Yes. std::vector::assign() has the same three forms. The deque version works in the same way, but it stores data in several blocks instead of one.