Search code examples
c++iteratorc++17const-iterator

insert_or_assign is allowing iterator


I have this piece of code:

auto it = my_map.lower_bound(my_key);

The following assert gives me error:

static_assert(std::is_same<decltype(it), std::map<K, V>::const_iterator>::value, "Error");

And the following one, is ok:

static_assert(std::is_same<decltype(it), std::map<K, V>::iterator>::value, "Error");

Then, the compiler is not giving me a const_iterator. Ok. But here:

my_map.insert_or_assign(it, my_key, some_val);

even with iterator (not const_iterator), the function is working. But, in this link, on insert_or_assign signatures, I only have const_iterator arguments. I also searched for the .h file on Visual Studio and this information matches. Tested on GCC 7.2+ and Visual Studio 2015, everything compiles and runs.

Why does it compile? Why insert_or_assign accepts iterator?


Solution

  • All containers are required to provide an iterator type that is convertible to const_iterator. See the Container requirements table

    X​::​iterator is required to be any iterator category that meets the forward iterator requirements. convertible to X::const_iterator.

    So a const_iterator is being constructed from the iterator returned by lower_bound in the call to insert_or_assign.