The most common way (not necessarily the most efficient way):
c.insert( c.end(), value );
where, of course, value should be suitable for container c (you can use decltype(c)::value_type ). In the case of an associative container, for example, map , this is std::pair .
This works for all standard containers except std::forward_list . For some containers, the item is then added to the end, for some c.end() is just a hint that can be ignored.
In addition to the comments, here are some advanced things;)
If you want to insert a known number of elements into a given container c (of type c ), and you want to be at least somewhat efficient, you must find the container of the container type that supports reserve() and calls it before inserting the elements.
The following method correctly defines reserve() (the link explains how):
template< typename C, typename = void > struct has_reserve : std::false_type {}; template< typename C > struct has_reserve< C, std::enable_if_t< std::is_same< decltype( std::declval<C>().reserve( std::declval<typename C::size_type>() ) ), void >::value > > : std::true_type {};
Now you can use it with std::enable_if_t for additional reservation of a place. An example might look like this:
template< typename C > std::enable_if_t< !has_reserve< C >::value > optional_reserve( C&, std::size_t ) {} template< typename C > std::enable_if_t< has_reserve< C >::value > optional_reserve( C& c, std::size_t n ) { c.reserve( c.size() + n ); } template< typename C, typename T, std::size_t N > void add_array( C& c, const std::array< T, N >& a ) { optional_reserve( c, N ); for( const auto& e : a ) { c.insert( c.end(), typename C::value_type( e ) );
add_array can now be called with all standard containers (except std::forward_list ), and it will call reserve() for std::vector and unordered associative containers.
As indicated above, explicit specialization or transshipment is not required for specific types of containers, it also works for non-standard containers if their interfaces are designed quite similarly to the interfaces of standard containers. (In fact, I had several such βhomemadeβ containers in the past and above, Just-Works β’)
A note on converting in the above code: the reason for converting T to C::value_type is to show that this would be the right place if necessary. In the example above, this may seem redundant, but in my real code, I call a class of special transformations to convert e (which are encoded strings) to the correct value type for any container.