使用结构的特定字符串元素定义 unordered_map 键

define unordered_map key with specific string element of struct

我是 unordered_map.I 的新手,想用下面定义的某个结构的特定字符串元素定义 unordered_map 散列 table 键:- hashtable.cpp写在下面:-

#include <tr1/unordered_map>
 #include <iostream>
 #include <stdio.h>
 using namespace std;
 using namespace std::tr1;
    struct row{
                string state;
                int population;
            };
    struct total{
                string key;
                row value;
            };
    int main ()
    {
        total data;
        unordered_map<data.key,data.value> country;
        data.key="Australia";
        data.value.state="Canberra";
        data.value.population=12000;
      return 0;
    }

我遇到了这样的错误:-

hashtable.cpp:17: error: ‘data’ cannot appear in a constant-expression
hashtable.cpp:17: error: ‘.’ cannot appear in a constant-expression
hashtable.cpp:17: error: ‘data’ cannot appear in a constant-expression
hashtable.cpp:17: error: ‘.’ cannot appear in a constant-expression
hashtable.cpp:17: error: template argument 1 is invalid
hashtable.cpp:17: error: template argument 2 is invalid
hashtable.cpp:17: error: template argument 3 is invalid
hashtable.cpp:17: error: template argument 4 is invalid
hashtable.cpp:17: error: template argument 5 is invalid
hashtable.cpp:17: error: invalid type in declaration before ‘;’ token

你做错了。也许,正确的做法是

int main ()
{
    total data{"Australia", {"Canbeera", 12000}};
    unordered_map<std::string,row> country;
    count.insert({ data.key, { data.value } });
  return 0;
}

检查此page以供参考

unordered_map<data.key,data.value> country;

您的意图显然是来自 c++11 及更高版本的内容

unordered_map<decltype(data.key),decltype(data.value)> country;

因为无论如何你都使用 tr1 扩展,我建议你至少为你的编译启用 C++11 语法,并从 std::.

中获取曾经是 tr1 的东西