代码之家  ›  专栏  ›  技术社区  ›  Sergej Fomin

C++不能引用地图的键

  •  2
  • Sergej Fomin  · 技术社区  · 6 年前
    #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;
                }
            } 
        }
    }
    

    你好当我试图编译此代码时,它会给我错误:

    “基本字符串”类型的绑定值<>'引用类型

    string& old_country = s.first;
    

    为什么会发生这种情况(它不会在下一个字符串中给出此错误,其中我通过引用指定了“s.second”)。

    编译器是ISOC++ +1Y(-STD= C++ +1Y)。

    非常感谢。

    1 回复  |  直到 6 年前
        1
  •  6
  •   Matthieu Brucher    6 年前
    const string& old_country = s.first;
    

    或者更好:

    const auto& old_country = s.first;
    

    旁注:为了可读性,添加 const

    您的地图对应的一对是:

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