这是我的一些代码:
#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;
if (!doca.load_file("a.xml") || !docb.load_file("b.xml"))
return 1;
for (auto& node: doca.child("site_entries").children("entry")) {
const char* id = node.child_value("id");
mapa[new std::string(id, strlen(id))] = node;
}
for (auto& node: docb.child("site_entries").children("entry"))
const char* idcs = node.child_value("id");
std::string id = new std::string(idcs, strlen(idcs));
if (!mapa.erase(id)) {
mapb[id] = node;
}
}
编译时出现这个错误:
src/main.cpp:16:13: error: no viable overloaded operator[] for type 'std::map<std::string, pugi::xml_node>'
mapa[new std::string(id, strlen(id))] = node;
最佳答案
您的类型不匹配。 mapa
的类型:
std::map<std::string, pugi::xml_node> mapa,
^^^^^^^^^^^^
但是你在做:
mapa[new std::string(id, strlen(id))] = node;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
string*
std::map
有两个 operator[]
重载:
T& operator[](const Key& );
T& operator[](Key&& );
在您的例子中,Key
是 std::string
。但是您正在尝试传入 std::string*
,因为它没有转换为 std::string
- 因此您会收到“没有可行的重载”的错误运算符[]
”。
你的意思是:
mapa[id] = node;
这一行的相同注释:
std::string id = new std::string(idcs, strlen(idcs));
C++ 不是 Java,你只需要:
std::string id(idcs, strlen(idcs));
或者简单地说:
std::string id = idcs;
关于c++ - 错误 : no viable overloaded operator[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705426/