what does list/map return when insert failed?
when insert new element to list/map, it returns the iterator pointed to the newly added element.
But if insert failed, what does list/map return? I have read the referen开发者_开发百科ces, when failed, list/map will not throw a exception.map::insert
returns pair of iterator and bool value. If insertion fails bool value is set to false
.
cplusplus site is very clear about what map::insert returns http://www.cplusplus.com/reference/stl/map/insert/
Return value The first version returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element that already had its same value in the map. The pair::second element in the pair is set to true if a new element was inserted or false if an element with the same value existed.
The second version returns an iterator pointing to either the newly inserted element or to the element that already had its same value in the map.
iterator is a member type, defined as a bidirectional iterator type. Dereferencing this iterator accesses the element's value, which is of type pair.
If insert cannot allocate the memory, bad_alloc
is thrown. In all other cases insert works perfectly. link
Update: It also needs to copy the inserted object which can throw any exception.
精彩评论