使用结构的特定字符串元素定义无序映射键

define unordered_map key with specific string element of struct

本文关键字:定义 元素 无序 映射 字符串 结构      更新时间:2023-10-16

我是unordered_map的新手。我想用下面定义的某个结构的特定字符串元素定义unordered.map哈希表键:-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;
}

查看此页面以获取参考

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

你的意图显然是从c++11到

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

因为您无论如何都使用tr1扩展,所以我建议您至少为编译启用C++11语法,并从std::中获取曾经的tr1内容。