Ajay
Ajay

Reputation: 18451

Why pair is required to insert into map?

Though I do not dislike it, but find it inconvinient to declare a pair<X,Y> object, or make a call to make_pair, in order to call map::insert. Why insert doesn't take two arguments instead to specify Key and Value respectively.

While I understand it is for compatibility with other STL containers, that exhibit value_type. But find method takes key_type which breaks this compatibility assertion. map has both key_type and mapped_type, so why cant map have:

iterator insert(const key_type&, const mapped_type&);

Yes, there are overloads of insert taking iterator(s). But this two-argument insert could have been mixed well.

Just one advantage I see is: less call stack usage.

EDIT: Just found out that insert is the only method that takes value_type, that is pair<X,Y>. Many other methods like find, erase, at, count, equal_range, lower_bound, upper_bound and operator[] take key_type.

Upvotes: 7

Views: 754

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477640

All standard library containers define a value_type member type, and their interfaces generically operate in terms of this value_type: insert, push_back, push_front. The new interface emplace adds a way of constructing a value_type object as if by:

value_type(std::forward<Args>(args)...)

Basically, there is no special interface provided for the satellite-data associative containers (i.e. maps) which is aware of the special structure of value_type (which is defined, not perfectly well-known, to bepair<const key_type, mapped_type>), with the exception of find and erase and operator[], which take key_type arguments.

It is perhaps an oversight of the standard, or perhaps it was never deemed to be a problem, since you can always use make_pair, make_tuple or forward_as_tuple, or emplace, to create map value types.

(There is one problem with insert and move-only mapped types that has surfaced and is subject of this recent proposal.)

Upvotes: 6

Related Questions