C++:带有无序映射的嵌套字典



我正在尝试编写一些代码,这些代码将允许我在C++中使用unordered_map对象创建一个字典。它基本上看起来像

string1
string2
int_vec1
string3
int_vec2
...

即,它是一个字符串和整数向量对的字典,由字符串索引。

我有以下简化示例的代码来说明:

#include <chrono>
#include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <ctime>
#include <string>
#include <unordered_map>
int main(int argc, char **argv) {
std::string key_0 = "key_0";
std::string key_01 = "key_01";
std::string key_02 = "key_02";
std::string key_1 = "key_1";
std::string key_11 = "key_11";
std::string key_12 = "key_12";
std::string key_13 = "key_13";
std::vector<int> val_01 = {1,2,3,4};
std::vector<int> val_02 = {1,2,3,4};
std::vector<int> val_11 = {1,2,3,4};
std::vector<int> val_12 = {1,2,3,4};
std::vector<int> val_13 = {1,2,3,4};
std::unordered_map<std::string, std::unordered_map<std::string, std::vector<int>>> my_dict;
my_dict.insert({key_0, std::pair<std::string, std::vector<int>>(key_01, val_01)});
}

然而,当我使用gcc 11.2.0版本编译它时,我得到了以下错误

test_make_nested_unordered_map.cpp:25:17: error: no matching function for call to ‘std::unordered_map<std::__cxx11::basic_string<char>, std::unordered_map<std::__cxx11::basic_string<char>, std::vector<int> > >::insert(<brace-enclosed initializer list>)’
25 |   my_dict.insert({key_0, std::pair<std::string, std::vector<int>>(key_01, val_01)});
|   ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

这个代码对我来说似乎很好。但我不知道为什么它不起作用。我将非常感谢在这方面的帮助。我的实际代码更复杂,但这只是一个简化的可复制示例。

感谢的帮助

编辑

感谢用户273K的回答。我能够让它更接近我的预期:这段代码运行时没有问题

#include <chrono>
#include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <ctime>
#include <string>
#include <unordered_map>

void print_string_vec2(std::vector<int> vec) {
for (auto s : vec) {
std::cout << s << " ";
}
std::cout << std::endl;
}
int main(int argc, char **argv) {
std::string key_0 = "key_0";
std::string key_01 = "key_01";
std::string key_02 = "key_02";
std::string key_1 = "key_1";
std::string key_11 = "key_11";
std::string key_12 = "key_12";
std::string key_13 = "key_13";
std::vector<int> val_01 = {1,2,3,4};
std::vector<int> val_02 = {1,2,3,4};
std::vector<int> val_11 = {1,2,3,4};
std::vector<int> val_12 = {1,2,3,4};
std::vector<int> val_13 = {1,2,3,4};
std::unordered_map<std::string, std::unordered_map<std::string, std::vector<int>>> my_dict;
my_dict.insert({key_0, {{key_01, val_01}}});
my_dict[key_0].insert({key_02, val_02});
my_dict.insert({key_1, {{key_11, val_11}}});
my_dict[key_1].insert({key_12, val_12});
my_dict[key_1].insert({key_13, val_13});
for (auto& u : my_dict) {
for (auto& v : u.second) {
std::cout << "(" << u.first << "," << v.first << "): ";
print_string_vec2(v.second);
}
}
}

运行时输出

(key_1,key_13): 1 2 3 4
(key_1,key_12): 1 2 3 4
(key_1,key_11): 1 2 3 4
(key_0,key_02): 1 2 3 4
(key_0,key_01): 1 2 3 4

没有从std::pairstd::unordered_map的转换。你似乎希望

my_dict.insert({key_0, {{key_01, val_01}}});

内部大括号是具有对初始值设定项的内部无序映射的初始值设定值列表。

最新更新