错误:没有可行的重载运算符[]

时间:2015-04-17 17:06:33

标签: c++ c++11

这是我的一些代码:

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

1 个答案:

答案 0 :(得分:5)

您的类型不匹配。 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&& );

在您的情况下,Keystd::string。但是您正试图传递std::string*,因为没有转换为std::string - 因此您会收到错误#34;没有可行的重载operator[]&#34 ;。

你打算做的是:

mapa[id] = node;

此行的评论相同:

std::string id = new std::string(idcs, strlen(idcs));

C ++不是Java,你只需这样做:

std::string id(idcs, strlen(idcs));

或简单地说:

std::string id = idcs;
相关问题