【问题标题】:Map::insert does not work [closed]Map::insert 不起作用[关闭]
【发布时间】:2014-10-08 19:43:17
【问题描述】:

我正在使用此代码向地图中插入一些元素。

raw.insert({ std::string(name), new raw_resource(data, length) });

第一个元素插入成功,但第二个没有。 地图类型是

std::map<std::string, raw_resource*, compare> raw;

比较代码

class compare
{
public:
    bool operator()(std::string s1, std::string s2)
    {
        return (s1.compare(s2) == 0);
    }
};

【问题讨论】:

  • std::map 只接受唯一键。如果 key 已经插入,则插入失败。
  • 定义“不起作用”并调整标题,以便简洁地总结问题。
  • 这不是std::map 的合法比较器。只需使用默认的 - 无论如何您都不会尝试做任何特别的事情。
  • @DejaVu but I used std::map::find with 100% existing key and it returned map::end() 这意味着密钥“100%”不存在。
  • @DejaVu - 我看到“test-vs”和“test_vs”。它们不是同一个字符串。但是想一想——如果编译器的map::find 被破坏了,你会考虑使用map 类做任何事情吗?为什么要为您认为已损坏的地图类编写比较函数?我什至可能不会使用整个编译器套件,更不用说map 类了。

标签: c++ stl


【解决方案1】:

查看参考:

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;

http://en.cppreference.com/w/cpp/container/map

std::map 接受一个比较器,判断第一个参数是否小于第二个参数。不是如果他们是平等的。否则无法构建二叉树。

您根本不需要为std::string 编写自己的比较器。已经为您定义了所有比较运算符:http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多