问题
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
?
回答1:
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
.
回答2:
Your lower_bound
call will give you a non-const iterator on non-const map. However, there is an automatic conversion from non-const iterator to const-iterator, so any function which requires const_iterator can be called with non-const iterator of the same type.
来源:https://stackoverflow.com/questions/50726153/insert-or-assign-is-allowing-iterator