简体   繁体   English

C ++无法引用地图键

[英]C++ Can't reference key of the map

#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;
            }
        } 
    }
}

Hello! 你好! When I try to compile this code it gives me error: 当我尝试编译此代码时,它给了我错误:

binding value of type 'basic_string<...>' to reference to type 'basic_string<...>' drops 'const' qualifier 将类型'basic_string <...>'的绑定值引用到类型'basic_string <...>'的引用将删除'const'限定词

for the string 对于字符串

string& old_country = s.first;

Why does this happen? 为什么会这样? (it doesn't give this error for the next string - where I assing "s.second" by reference). (对于下一个字符串,它不会给出此错误-我通过引用将“ s.second”设置为此处)。

Compiler is ISO C++ 1y (-std=c++1y). 编译器为ISO C ++ 1y(-std = c ++ 1y)。

Thank you. 谢谢。

const string& old_country = s.first;

Or even better: 甚至更好:

const auto& old_country = s.first;

Side note: for readability, add the const even for auto. 旁注:为了便于阅读,甚至为auto添加const

The pair for your map is: 您的地图对是:

std::pair<const std::string, string>

because the key cannot be modified due to the tree constraint. 因为键由于树约束而不能修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM