【发布时间】:2018-03-19 17:46:08
【问题描述】:
使用 C++14(也应该影响 C++11)我对 auto 在通过 std::unordered_map 的基于范围的 for 循环中感到困惑,而不是使用像 std::pair<int, int> 这样的确切类型在下面的代码中。
更具体地说,我对示例有一些(相关)问题:
- 问题 0:(循环 0)为什么不允许
std::pair<int, int> &而循环 1 中的auto &是? - 问题 1:(循环 1)为什么/如何/何时
auto与确切类型不同(例如循环 0 中的std::pair<int, int>)? - 问题 2:(循环 2)为什么这与循环 3 中的指针不同?
问题 3:(循环 3)为什么所有映射条目的指针都相同?
问题 4(续 0 和 1):我知道基于范围的 for 循环使用迭代器。但是为什么我可以使用
auto(循环1)引用非常量的std::unordered_map,但在使用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
【问题讨论】:
-
A
std::unordered_map<int,int>不包含std::pair<int,int>的实例。它拥有std::pair<const int, int>。所以你所有的pair<int,int>都是临时副本。我认为这回答了您的所有 5 个问题。 -
在此处查看
value_type:en.cppreference.com/w/cpp/container/unordered_map 请注意,在您的情况下,它将是std::pair<const int, int> -
哇,感谢您提供快速而有用的答案!这是我在这里的第一个问题,我很高兴有你们。 :-)
-
std::map<K, V>::value_type的类型是什么?不是std::pair<K, V>。
标签: c++ c++11 for-loop stl auto