std::sort with equal elements gives Segmentation fault(具有相等元素的 std::sort 给出分段错误)
问题描述
我有一个存储指针的容器.我试图根据指针指向的相应对象中的数据成员以非递增顺序对这些指针进行排序.就我而言,许多对象可能对该数据成员具有相同的值.
I have a container storing pointers. I am trying to sort these pointers in non-increasing order based on a data member in the corresponding objects pointed by the pointers. In my case, it is possible that many objects have the same value for that data member.
以下是说明问题的简短代码.对排序函数的调用给出了分段错误.奇怪的是,如果容器中有 16 个元素指向具有相同双精度值的对象,则排序似乎有效.但是,如果我有 17 个元素指向具有相同值的对象,则会出现段错误.
The following is a short code to illustrate the problem. The call to the sort function is giving a Segmentation fault. The weird thing about this is, if I have 16 elements in the container pointing to objects with same value for the double, the sort seems to work. But if I have 17 elements pointing to objects with same value, it gives a seg fault.
谁能解释一下为什么会这样?
Can anyone please explain why this happens?
#include <iostream>
#include <algorithm>
#include <deque>
//some class
class A {
public:
double a;
A(double aval);
};
A::A(double aval) : a(aval) {}
//compare class
struct cmp_A : std::greater_equal<A*> {
bool operator() (const A* x, const A* y) const;
} cmp_A_obj;
//greater_equal comparison
bool cmp_A::operator() (const A* x, const A* y) const {
return (x->a >= y->a);
}
int main() {
std::deque<A*> Adeque;
//insert 17 A pointers into the container
for(int i = 1; i<=17; i++) {
Adeque.push_back(new A(5));
}
//This call to sort gives a Segmentation fault
std::sort(Adeque.begin(), Adeque.end(), cmp_A_obj);
for(std::deque<A*>::iterator i = Adeque.begin(); i!= Adeque.end(); i++) {
std::cout << "|" << (*i)->a;
}
std::cout << std::endl;
}
推荐答案
你的比较必须实现 严格弱排序.小于或等于不满足这一点.它应该等同于在运算符 <
和 >
中实现的小于"或大于",例如整数.
Your comparison must implement a strict weak ordering. Less than or equal does not satisfy this. It should be equivalent to "less than" or "greater than" as implemented in operators <
and >
for, say, integers.
元素的相等性通过应用此排序两次来确定:
Equality of elements is determined by applying this ordering twice:
(!cmp(a,b)) && (!cmp(b,a)); // if this is false, a == b
这篇关于具有相等元素的 std::sort 给出分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有相等元素的 std::sort 给出分段错误
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01