今天这让我很困惑。
我无法理解为什么下面的代码在最终插入 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;
}
最佳答案
您的比较功能已损坏。你可能是这个意思:
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<i2
和 i2<i3
是真的。
关于c++ - std::map 的比较器函数中的段错误/未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54102309/