c++ - 缺少用于 map 初始化的构造函数

标签 c++ xml c++11 xml-parsing

我在之前的主题上得到了一些帮助,在该主题中我不得不更改我的映射以将 int 与字符串结合使用。当我这样做时,它给了我一个不同的问题。这是问题:

src/main.cpp:11:29: error: no matching constructor for initialization of
      'std::map<int, std::string>'
  ...tagMap {{"1", "data"}, {"2", "entry"}, {"3", "id"}, {"4", "content"}};
     ^      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

似乎这个问题(我在另一个主题上查找过)似乎暗示了一个事实,即问题与使构造函数采用 const 引用有关?我真的不明白如何实现这一点。

#include "pugi/pugixml.hpp"

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

int main()
{
    pugi::xml_document doca, docb;
    std::map<std::string, pugi::xml_node> mapa, mapb;
    std::map<int, std::string> tagMap {{"1", "data"}, {"2", "entry"}, {"3", "id"}, {"4", "content"}};

    if (!doca.load_file("a.xml") || !docb.load_file("b.xml")) {
        std::cout << "Can't find input files";
        return 1;
    }

    for (auto& node: doca.child(tagMap[1]).children(tagMap[2])) {
        const char* id = node.child_value(tagMap[3]);
        mapa[id] = node;
    }

    for (auto& node: docb.child(tagMap[1]).children(tagMap[2])) {
        const char* idcs = node.child_value(tagMap[3]);
        if (!mapa.erase(idcs)) {
            mapb[idcs] = node;
        }
    }
}

如有任何帮助,我们将不胜感激。

最佳答案

像这样尝试:

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

using namespace std;

int main() {
   std::map<int, std::string> tagMap {make_pair(1, "data"), make_pair(2, "entry")};
}

编辑:没有make_pair功能的版本也有效:

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

using namespace std;

int main() {
   std::map<int, std::string> tagMap {{1, "data"}, {2, "entry"}};
}

你唯一需要记住的是,你不应该依赖编译器 const string literal 来进行数字转换...

关于c++ - 缺少用于 map 初始化的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804601/

相关文章:

c++ - Linux上适用于C++的任何更智能的编译系统

android - <TableLayout><TableRow><LinearLayout> 讨厌我。强制关闭运行。安卓

javascript - IE - JQuery 在 $.each 循环中将子节点附加到 XML

c++ - C++ lambda 表达式的生命周期是多少?

具有抽象工厂的派生类的 C++11 单例

c++ - 如何定义在 SFML 游戏中使用多少 CPU?

c++ - 通过结构和重载运算符包装 CUDA 共享内存定义和访问

c++ - 计算独特项目的更好方法

xml - 文件 ://. 是有效的 URI吗?

c++ - 现代 C++ 中的类型删除分配器