是否可以将具有地图类型值的一对插入到另一个地图中?

Is it possible to insert a pair with a map type value into another map?

尝试查找此内容,但似乎无法找到详细的答案。假设我有一张地图:

std::map<int, string> categoryMap;

并且我想创建第二个地图,其中包含键和值,只有在与第一个地图的特定键相关联时才能访问这些键和值。第二张地图也类似:

std::map<int, string> itemMap;

我尝试做一些插入函数来尝试这个

categoryMap.insert(std::pair<int, map<int, string>>(itemValue, itemMap));

我收到的错误声称 "no instance of overloaded function matches the argument list." 是否有另一种方法可以解决这个问题,或者这是不可能的?

可以,但是您尝试插入的对的类型 (template parameter) int, map<int, string> 与地图类型不匹配 int, string

为了能够 运行 您的插入调用:

categoryMap.insert(std::pair<int, map<int, string>>(itemValue, itemMap));

categoryMap 必须使用与您要插入的项目相同的模板类型进行定义,即:

std::map<int, map<int, string>> categoryMap;

See it online.

#include <iostream>
#include <string>
#include<map>

using namespace std;

int main()
{
    std::map<int, std::map<int, string>> categoryMap;
    std::map<int, std::string> itemMap;
    itemMap.insert(std::pair<int, std::string>(1, "abc"));
    itemMap.insert(std::pair<int, std::string>(2, "xyz"));
    categoryMap.insert(std::pair<int, std::map<int, std::string>>(1, itemMap));
}