插入新键时它会更改现有键值的地址吗?

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

在我的代码中,会在std::map中插入或删除,但不会更改现有键的值。 当 inserting/deleting 个新密钥时,它会更改现有密钥值的地址吗?

int main()
{

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

    return 0;
}

而且结果总是一样的。。。所以对老key没有影响? 顺便问一下,unordered_map 呢?

插入或删除其他元素时,现有元素的地址不会改变。换句话说,除非删除特定元素,否则对元素的引用不会失效。

这适用于所有基于节点的容器,包括关联容器(映射、集合、无序变体、它们的多变体)和链表。对于基于数组的双端队列、向量或字符串,情况并非如此。

无序关联容器的迭代器可能会在插入时失效,以防重新散列;这不会影响地址。

基于std::map<Key,T,Compare,Allocator>::operator[]迭代器和引用都不会无效:

[…]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.

对于std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::operator[],迭代器可能会失效,但引用不会:

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.