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

标签 c++ c++11 for-loop stl auto

使用 C++14(应该也会影响 C++11)我对 auto 感到困惑在通过 std::unordered_map 的基于范围的 for 循环中, 而不是使用像 std::pair<int, int> 这样的精确类型在下面的代码中。

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

  • 问题 0:(循环 0)为什么是 std::pair<int, int> &不允许但auto &在循环 1 中是?
  • 问题 1:(循环 1)为什么/如何/何时做 auto与确切类型不同(例如循环 0 中的 std::pair<int, int>)?
  • 问题 2:(循环 2)为什么这与循环 3 中的指针不同?
  • 问题 3:(循环 3)为什么所有映射条目的指针都相同?

  • 问题 4(继续 0 和 1):我知道基于范围的 for 循环使用迭代器。但为什么我可以遍历 std::unordered_map引用非常量使用 auto (循环 1),但在使用 std::pair 时不是(循环 0)?


#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绑定(bind)到 std::pair<int, int> 类型的临时对象由 std::pair<const int, int> 构建.

关于c++ - 为什么我可以在通过 'auto' 的基于范围的 for 循环中使用 'std::pair' 而不是 'std::unordered_map' 对非常量的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49369293/

相关文章:

c++ - tolower() 不适用于 C++ 中的 Ü,Ö

javascript - Vue 指令 v-for ="thing in collection"vs "thing of collection"

c++ - C++ 中嵌套 for 循环的一行代码

php - 使用条件语句循环时出现 fatal error 导致内存耗尽

java - Java 中的 char** 等价物

c++ - 如何渲染拉伸(stretch)到全屏原始分辨率的低分辨率场景?

c++ - 在 C++ 中,如何有效地在两个类之间共享数据?

c++ - 分布在 -DBL_MAX 和 DBL_MAX 之间的随机 double

c++ - C++ 编译器能否消除未读取的 volatile 局部变量

c++ - C++中make_shared和常规shared_ptr的区别