c++ - std::map 的比较器函数中的段错误/未定义行为

标签 c++ c++11 segmentation-fault undefined-behavior

今天这让我很困惑。

我无法理解为什么下面的代码在最终插入 test_map 时出现段错误。使用 emplace()、insert() 都按预期工作,但使用 [] 运算符失败。我已经阅读了 [] 的相关 C++ 文档,但下面观察到的行为似乎与我所阅读的内容不符。

我在 GDB 中单步执行并注意到在比较器函数中尝试比较字符串时它失败了。

#include <iostream>
#include <map>
#include <iostream>

class Testkey {
public:
    std::string s1;
    int64_t id;
    Testkey(const char* s1_, int64_t id_): s1(s1_), id(id_) {}

    bool operator<(const Testkey& rhs) const {
        if (s1 < rhs.s1)
            return true;
        if (id < rhs.id)
            return true;
        return false;
    }
};

int main() {
    Testkey i1("69739", 748072524);
    Testkey i2("69728", 52608624);
    Testkey i3("69725", 750212380);
    Testkey i4("68988", 55027788);

    std::map<Testkey, int> test_map;
    test_map[i1] = 1;
    test_map[i2] = 2;
    test_map[i3] = 3;
    std::cout << "hmm.." << std::endl;
    test_map[i4] = 4; // seg faults here in comparator function...
    std::cout << "done" << std::endl;
    return 0;
}

我在这里附上了回复 https://repl.it/repls/RundownSparklingComment

最佳答案

您的比较功能已损坏。你可能是这个意思:

bool operator<(const Testkey& rhs) const {
    if (s1 < rhs.s1)
        return true;
    if (s1 > rhs.s1)
        return false;
    if (id < rhs.id)
        return true;
    return false;
}

比较函数用于std::map必须定义一个 strict weak ordering要插入或比较的对象的数量,而您的函数则不会,因为这两个 i3<i2i2<i3是真的。

关于c++ - std::map 的比较器函数中的段错误/未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54102309/

相关文章:

C++ Segmentation Fault while循环解析链表有序插入条件语句中的Segmentation Fault

c++ - 为什么 boost::noncopyable 需要继承

c++ - 医疗 3D 规划软件的最佳技术

java - Android:获取 C++ std::string 直至 JNIEXPORT 被意外清除

c++ - 我可以在非标准容器上使用迭代器库的访问函数吗?

segmentation-fault - 为什么我的 Gdk/cairo 类会导致段错误?

c++ - 调试堆内存泄漏检测 - 奇怪的结果?

c++ - Visual C++ 2005 探查器

c++ - 将 std::lock_guard 与 try_lock 一起使用

C++ 段错误问题