2015-04-22 54 views
0

我在前一个主题上得到了一些帮助,我不得不改变我的地图使用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"}}; 
    ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

这似乎是问题(我抬头另一个话题),似乎暗示的事实,问题是让你的构造做取常量引用?我真的不明白如何实现这一点。

#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; 
     } 
    } 
} 

任何帮助,将不胜感激。

+1

为什么“1”,“2”等?你的地图说'int'。 – chris

回答

4

尝试某事像:

#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"}}; 
} 

,你需要记住的唯一的事情是,你不应该依赖编译器常量字符串文字到数字转换...

+0

谢谢你的回复。虽然这让我更接近仍然给了我错误:'src/main.cpp:20:30:错误:没有可行的从'mapped_type'(又名 'std :: __ 1 :: basic_string ')转换为' const char_t *'(aka'const char *') for(auto&node:doca.child(tagMap [1])。children(tagMap [2])){ ^ ~~~~~~~~''' –

+1

第20行尝试:'auto id'而不是'const char * id',同样在第25行。 –

+0

这似乎给了我同样的错误src/main.cpp:20:30错误:没有可行的转换从'mapped_type'(aka'std :: __ 1 :: basic_string ')到 'const char_t *'(aka'const char *') for(auto&node:doca.child(tagMap [1])。children tagMap [2])){'''。这是一个相关的错误,或者我应该打开一个新的问题 –