我正在嘗試撰寫一些代碼,允許我使用 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
uj5u.com熱心網友回復:
沒有從std::pair到的轉換std::unordered_map。你似乎希望
my_dict.insert({key_0, {{key_01, val_01}}});
內部大括號是帶有對初始化器的內部無序映射的初始化器串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516295.html
