Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why insert_or_assign doesn't have iterator overload?

Issue

In C++17, associative containers in standard library will have insert_or_assign member function, which will do what its name suggests. Unfortunately, it seems like it doesn't have iterator based interface for bulk insert/assign. I even tried to compile small example, and from the compiler error, compiler couldn't find suitable overload, and neither candidate was reasonably close to iterator based interface.

Question

Why C++17 didn't include iterator based insert_or_assign for operations in bulk? Was there any technical reasons? Design issues?

My assumptions and ideas

I don't see any technical reason to not add iterator based bulk insertion/addition. It seems quite doable. It needs to lookup the key anyway, so I don't see any violations of "Don't pay for what you don't use".

Actually not having the overload makes standard library less consistent, and kind of going against itself. Plain insert supports it, so I'd expect insert_or_assign to support that too. I don't think that not having the overload will make it "Easier to use correctly, and harder to use incorrectly".

The only clue left is this notice from cppreference:

insert_or_assign returns more information than operator[] and does not require default-constructibility of the mapped type.

I'm not sure why this might be a limitation, as the associative container has access to all of the internals and doesn't need to deal with operator[] at all.

Binary compatibility is not applicable here, if I didn't forget anything. Modification will be in a header, and everything will need to recompile anyway.

I couldn't find any associated paper either. Splicing maps and sets doesn't seem to mention it. The feature looks like a phantom.

Standard could at least include insert_assign_iterator, so that one could write std::copy(input_first, input_last, insert_assign_iterator{map});, but standard includes neither.

like image 958
Incomputable Avatar asked Nov 23 '17 20:11

Incomputable


Video Answer


1 Answers

insert_or_emplace is intended to be a better form of doing some_map[key] = value;. The latter requires that the mapped_type is default constructible, while insert_or_emplace does not.

What you're talking about is similar, but different. You have some range of key-value pairs, and you want to stick all of those values into the map, whether they have equivalent keys or not. This was not the problem that these functions were created to solve, as evidenced by the original proposal for them.

It's not that they're necessarily a bad idea. It simply wasn't the problem the function was added to solve.

like image 116
Nicol Bolas Avatar answered Sep 21 '22 03:09

Nicol Bolas