【问题标题】:define unordered_map key with specific string element of struct使用结构的特定字符串元素定义 unordered_map 键
【发布时间】:2016-02-07 12:31:55
【问题描述】:

我是 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

【问题讨论】:

  • 你需要用类型实例化std::unordered_mapunordered_map&lt;std::string,row&gt; country;

标签: c++ struct hashtable unordered-map


【解决方案1】:

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

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

查看此page 以供参考

【讨论】:

  • 感谢您的回复,但是如果我想定义字符串的结构元素类型的键,我必须做什么
  • 你想定义结构元素的字符串作为键?
  • @Raule 是的,正如您从上面看到的那样,总计结构有两个元素字符串键和值行。那么我如何将键的结构定义为键?
  • 我们已经在这样做了。我们有 data 作为结构对象,data.key 是那里的关键。
  • 但它告诉我上面的错误我该怎么办?我已经像你说的那样定义了
【解决方案2】:

unordered_map&lt;data.key,data.value&gt; country;

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2021-02-11
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多