Reputation: 393
I am new to C++, I got confused about the c++ reference, for example, the std::map::insert reference, at the beginning, it has :
pair<iterator,bool> insert (const value_type& val);
template <class P> pair<iterator,bool> insert (P&& val);
iterator insert (const_iterator position, const value_type& val);
template <class P> iterator insert (const_iterator position, P&& val);
template <class InputIterator>
void insert (InputIterator first, InputIterator last);
void insert (initializer_list<value_type> il);
In the later example, it uses the insert like this:
mymap.insert ( std::pair<char,int>('z',200) );
From which line of the reference can I know that I can use the insert
function as above?
Upvotes: 1
Views: 212
Reputation: 60969
std::pair<char const, int>
is the value_type
of mymap
. The first insert
overload you quoted takes a const
-reference to value_type
.
Using a standard library reference requires basic knowledge of the language and corresponding library parts. Looking up a member function without understanding of the class it is a member of will, in most of the cases, not work out well. If you have a look at the reference for map you'll see that value_type
is defined as pair<const key_type, mapped_type>
which fits here since pair<char, int>
is convertible to pair<char const, int>
-- you also need to know how pair
works.
Upvotes: 1
Reputation: 43662
Assuming that you have a std::map<char,int>
, the line
mymap.insert ( std::pair<char,int>('z',200) );
is allowed since map defines the single element constructor
single element (1)
pair<iterator,bool> insert (const value_type& val);
template <class P> pair<iterator,bool> insert (P&& val);
the second one should kick in if you're using C++11. In C++03 only the first one is available.
The documentation says
Member type value_type is the type of the elements in the container, defined in map as
pair<const key_type,mapped_type>
thus std::pair<char,int>
is the value_type
of your map and the insertion is valid (a temporary can bind to a lvalue const reference or rvalue references in C++11).
I'm not suggesting to also take a look at cppreference since it might be even less understandable if you had problems with cplusplus.com, but generally I would recommend it.
Upvotes: 1
Reputation: 9619
If you read the Parameters section on the same page below, you will find the following description for val
:
Value to be copied to (or moved as) the inserted element.
Member type value_type is the type of the elements in the container, defined in map as pair<const key_type,mapped_type>
which clearly states that value_type
is the type of the elements in the container, defined in map
as pair<const key_type,mapped_type>
Upvotes: 1