c++ - 错误 : no viable overloaded operator[]

标签 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;

最佳答案

您的类型不匹配。 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 - 因此您会收到“没有可行的重载”的错误运算符[]”。

你的意思是:

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/

相关文章:

c++ - 离开作用域时调用函数

c++ - 为什么我会得到具有相同链接行的 undefined reference ?

C++ Builder DBGrid 在 xlsx 文件中导出到 Excel

c++ - 不匹配的符号是完整的展示塞子还是我可以部分信任它们来提取线索?

c++ - 删除 std::vector 中的最后 n 项时是否进行了优化

c++ - 为什么 `operator<<` 的 `basic_ostream` 的右值重载会返回左值引用?

c++ - 将 Boost::Beast 用于 CPU 密集型 REST API,我应该使用异步还是同步方式来实现它们以获得更好的延迟?

c++ - C++11 中具有对齐元素的 std::array 类型

c++ - CRTP 和生命周期延长

c++ - 我缺少什么?