为什么我可以在 'std::unordered_map' 的基于范围的 for 循环中使用 'auto' 而不是 'std::pair' 的非常量引用?

Why can I use a reference to non-const with 'auto' but not with 'std::pair' in range-based for-loop through 'std::unordered_map'?

使用 C++14(应该也会影响 C++11)与使用 std::unordered_map 相比,我对 auto 在基于范围的 for 循环中感到困惑确切类型如下面代码中的 std::pair<int, int>

更具体地说,我对这个例子有一些(相关的)问题:


#include<iostream>
#include <unordered_map>
#include <utility>

int main()
{
    std::unordered_map<int, int> map;
    map[3] = 333;
    map[2] = 222;
    map[1] = 111;

    // loop 0
    // QUESTION 0: Why is `std::pair<int, int> &` not allowed but `auto &` in loop 1 is?
    // for(std::pair<int, int> & pair : map)
    //     pair.second++;

    // loop 1
    for(auto & pair : map)
        // QUESTION 1: Why/How/When does `auto` differ from the exact type (like `std::pair<int, int>` in loop 0)?
        pair.second++;

    // loop 2
    for(auto const & pair : map)
        // QUESTION 2: Why are this different pointers than in loop 3?
        std::cout << pair.first << " (" << &pair.first << ") : " << pair.second << " (" << &pair.second << ")" << std::endl;

    // loop 3
    for(std::pair<int, int> const & pair : map)
        // QUESTION 3: Why are this the same pointers for all map entries?
        std::cout << pair.first << " (" << &pair.first << ") : " << pair.second << " (" << &pair.second << ")" << std::endl;
    return 0;
}

您可以 运行 此处的代码:https://www.onlinegdb.com/rkBkKDatf

std::unordered_map 的值类型是 std::pair<const Key, T>。参见 the documentation at cppreference.com

因此,您不能使用 std::pair<int, int>& 作为类型来迭代此类对象的内容。


这就是为什么

for(std::pair<int, int> & pair : map) { ... }

无效。


以下作品

for(auto const & pair : map)

因为类型是由编译器为您推导的。


以下作品

for(std::pair<int, int> const & pair : map)

因为 pair 绑定到 std::pair<int, int> 类型的临时对象,该对象由 std::pair<const int, int>.

构造