简体   繁体   English

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

[英]Error: no viable overloaded operator[]

This is a bit of my code: 这是我的代码:

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

When compiling I get this error: 编译时出现此错误:

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;

You have a type mismatch. 您的类型不匹配。 mapa is of type: mapa类型:

std::map<std::string, pugi::xml_node> mapa,
         ^^^^^^^^^^^^

But you're doing: 但是你在做:

mapa[new std::string(id, strlen(id))] = node;
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         string*

std::map has two overloads of operator[] : std::map有两个operator[]重载:

T& operator[](const Key& );
T& operator[](Key&& );

In your case, Key is std::string . 在您的情况下, Keystd::string But you're trying to pass in std::string* , for which there is no conversion to std::string - hence you get an error for "no viable overloaded operator[] ". 但是,您尝试传递std::string* ,但无法将其转换为std::string ,因此会收到“没有可行的重载operator[] ”的错误消息。

What you meant to do was: 您的意思是:

mapa[id] = node;

Same comment for this line: 此行的注释相同:

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

C++ is not Java, you just do: C ++不是Java,您可以这样做:

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

or simply: 或者简单地:

std::string id = idcs;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM