std::map 上基于范围的循环迭代需要解释

roi*_*mon 1 c++ range-based-loop

以下代码运行正常

#include<iostream>
#include<map>
#include<algorithm>
#include<string>
#include<vector> using namespace std;

int main() {
    std::map<int, std::string> m;
    m[0] = "hello";
    m[4] = "!";
    m[2] = "world";
    for (std::pair<int, std::string> i : m)
    {
        cout << i.second << endl;
    }
    return 0; }
Run Code Online (Sandbox Code Playgroud)

但是,如果我将 for 循环替换为

for (std::pair<int, std::string>& i : m)
{
    cout << i.second << endl;
}
Run Code Online (Sandbox Code Playgroud)

不管用。我明白'initializing': cannot convert from 'std::pair<const int,std::string>' to 'std::pair<int,std::string> &' 但是,

for (auto& i : m)
{
    cout << i.second << endl;
}
Run Code Online (Sandbox Code Playgroud)

正在工作,而且如果我执行以下操作

for (float& i : v)
{
    cout << i << endl;
}
Run Code Online (Sandbox Code Playgroud)

我没有遇到这个问题。这是为什么?

小智 5

Map 中的 key 是无法更改的,因此如果通过引用获取键值对, key 必须是const

在您的示例中,int变量是一个键,如果您pair通过引用获取,则可以修改该键,这是地图无法完成的。

看一下map::value type: https: //en.cppreference.com/w/cpp/container/map