The C++ sequence containers
(vector
, forward_list
, list
, and deque
)
all have an assign
method. For example, std::vector
has
(quoting cppreference.com):
void assign( size_type count, const T& value );
template< class InputIt >
void assign( InputIt first, InputIt last );
void assign( std::initializer_list<T> ilist );
These all have semantics that are, as far as I can tell, the same as
using operator=
on a temporary constructed using the arguments to the
assign
method. Why have a separate method to do, for example:
vec.assign({1,2,3});
instead of just:
vec = {1,2,3};
?
Meanwhile, the C++ associative containers such as std::map
do not have
an assign
method. Why not? What reason is sufficiently compelling
for the sequence containers to have it but not associative containers?
In particular, my initial guess for why sequence containers have
assign
is it avoids creating a temporary in the applicable
circumstance, but the same reasoning would apply to the associative
containers, right? (And with move assignment, creating the temporary is
probably insignificant anyway.)
This question has a practical application: I am creating a container
that has characteristics of both a sequence and associative container,
and wondering if there is a good reason to supply an assign
method for
it.