【问题标题】:fill nested std::map with insert operator用插入运算符填充嵌套的 std::map
【发布时间】:2014-05-05 14:15:30
【问题描述】:

我有以下代码:

#include <iostream>
#include <utility>
#include <map>

using namespace std;

int main()
{
map<int, map<string, int> > mapa;

// way A
mapa[10]["aaa"] = 20;

// way B -> Compilation Error
pair<int, pair<string, int> > par(10, make_pair("aaa", 20));
mapa.insert(par);


return 0;
}

我知道填充地图的“方式 A”是有效的。 我想使用“方式 B”,但它会引发编译错误: 错误:没有匹配函数调用‘std::map, int>::map(const std::pair, int>&)’

如何使用插入运算符填充嵌套地图。

Pd:我不使用 [] 运算符,因为它需要定义默认构造函数,因为我使用的是来自 Boost 的 time_period 对象,所以我没有。

【问题讨论】:

    标签: map insert nested


    【解决方案1】:

    您的地图类型是map of (int -&gt; map of (string -&gt; int)),但您正尝试插入map of (int -&gt; pair (string, int)) 类型的条目。 pair 不是 map,因此出现错误。

    编辑

    根据the documentation,调用map的[]操作符相当于进行了一系列其他操作:

    mapped_type& operator[] (const key_type& k);

    对该函数的调用等效于:
    (*((this->insert(make_pair(k,mapped_type()))).first)).second

    所以在你的情况下,调用mapa[10]["aaa"] = 20; 相当于:

    (*(( (*((mapa.insert(make_pair(10,map<string, int>()))).first)).second
      .insert(make_pair("aaa",20))).first)).second
    

    但我相信如果键 10aaa 存在,则不会在地图中插入任何元素。我建议您仔细阅读文档并测试预期的行为。

    【讨论】:

    • 是的,你是对的。我明白什么是编译错误。我想知道的是如何做类似于“方式 A”但使用插入运算符而不是 [] 运算符的事情。
    • 它实际上有点复杂,因为密钥可能存在。如果是,则该值(即地图)存在,您必须对其进行更新。如果没有,您必须创建地图。
    猜你喜欢
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多