使用结构的特定字符串元素定义无序映射键
define unordered_map key with specific string element of struct
我是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内容。
相关文章:
- 如何绘制自定义形状的元素?
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 从自定义类获取对象向量中的 max 元素
- 如何访问宏中定义的数组元素
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 从自定义数据类型向量中删除重复元素
- 如果我想从类型"T"定义元素的容器(来自 STL),那么"T"必须使用默认构造函数?
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- C++ - 按自定义数据类型向量的值删除元素
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- const 数组,用于在数组长度定义中使用其元素或为模板参数提供值
- 如何找到具有用户定义谓词的向量的最大元素
- 使用自定义比较器C++映射,不插入所有元素
- 为什么可以在长度为 0 的数组中添加定义元素 C++.
- (XAML UWP)定义元素,包括跨多个页面(C )使用的事件
- 使用 C++ 中的自定义元素进行 Const 结构初始化
- 如何在int数组中查找用户定义元素的数量
- C++:如何在同一类的不同函数中定义元素