C++无法引用地图的键

Ser*_*min 2 c++ stdmap

#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <string>

using namespace std;

int main() {
    int steps;
    map<string, string> countries;
    cin >> steps;
    for (int i = 0; i < steps; ++i) {
        string command;
        cin >> command;
        if(command == "CHANGE_CAPITAL") {
            for(auto& s : countries) {
                string& old_country = s.first;
                string& old_capital = s.second;
            }
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

你好!当我尝试编译此代码时,它给了我错误:

'basic_string <...>'类型的绑定值引用类型'basic_string <...>'drop'const'限定符

对于字符串

string& old_country = s.first;
Run Code Online (Sandbox Code Playgroud)

为什么会这样?(它不会为下一个字符串提供此错误 - 我通过引用来协助"s.second").

编译器是ISO C++ 1y(-std = c ++ 1y).

谢谢.

Mat*_*her 6

const string& old_country = s.first;
Run Code Online (Sandbox Code Playgroud)

甚至更好:

const auto& old_country = s.first;
Run Code Online (Sandbox Code Playgroud)

附注:为了便于阅读,请const为auto 添加偶数.

你的地图对是:

std::pair<const std::string, string>
Run Code Online (Sandbox Code Playgroud)

因为树约束不能修改密钥.

  • 我会说'const auto&old_country = s.first;`更好.它将阻止下一个看OP的代码与OP现在具有相同的混淆. (2认同)