will it change the address of a existed key's value when inserting new keys?

Viewed 117

In my code,there will be inserting or deleting in a std::map,but not change the value of a existed key. will it change the address of a existed key's value when inserting/deleting new keys ?

int main()
{

    std::map<int,int> m;
    for(int i(0);i<100000;i++){
        m[i];
        std::cout<< &m[0]<<std::endl;
    }

    return 0;
}

and the result is always the same...So it just won't have influence on old keys? By the way ,what about the unordered_map?

2 Answers

The address of existing elements do not change when other elements are inserted or removed. In other words, references to the elements are not invalidated unless that particular element is erased.

This is true for all node based containers which include the associative containers (map, set, unordered variants, multi variants of them) and linked lists. It is not true for the array based deque, vector nor string.

Unordered associative containers may have their iterators invalidated upon insertion in case of rehashing; this does not affect the address.

Based on std::map<Key,T,Compare,Allocator>::operator[] neither the iterators nor the references become invalid:

[…]Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.[…]No iterators or references are invalidated.

For std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::operator[] the iterators may become invalid, but not the references:

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist. [...] If an insertion occurs and results in a rehashing of the container, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated.

Related