我有这个代码:
QVector<LogEvent *> currentItems;
//add a bunch of LogEvent objects to currentItems
qSort(currentItems.begin(), currentItems.end());
这是我的 LogEvent 类:
日志事件.h:
//LogEvent.h
class LogEvent : public QTreeWidgetItem {
public:
LogEvent();
LogEvent(QDateTime, LogEvent *parent = 0);
~LogEvent();
bool operator<(const LogEvent *);
bool operator>(const LogEvent *);
bool operator<=(const LogEvent *);
bool operator>=(const LogEvent *);
bool operator==(const LogEvent *);
private:
QDateTime timestamp;
};
日志事件.cpp:
//LogEvent.cpp
LogEvent::LogEvent()
{
}
LogEvent::LogEvent(QDateTime timestamp, LogEvent *parent)
: QTreeWidgetItem(parent)
{
this->timestamp = timestamp;
}
bool LogEvent::operator<(const LogEvent * event) {
return (this->timestamp < event->timestamp);
}
bool LogEvent::operator>(const LogEvent * event) {
return (this->timestamp > event->timestamp);
}
bool LogEvent::operator<=(const LogEvent * event) {
return (this->timestamp <= event->timestamp);
}
bool LogEvent::operator>=(const LogEvent * event) {
return (this->timestamp >= event->timestamp);
}
bool LogEvent::operator==(const LogEvent * event) {
return (this->timestamp == event->timestamp);
}
在我进行排序后,currentItems 中的 LogEvent 对象没有正确排序。我很确定我的运算符重载正在工作。
当我做这样的事情时:
std::cout << currentItems[0]<=currentItems[1]?"T":"F";
它将输出正确的值。
那么我哪里做错了,我该如何改正呢?
最佳答案
qSort 正在对指针进行排序,而不是对这些指针指向的对象进行排序。如果你想用 qSort 对 LogEvents 进行排序,你将不得不按值而不是按引用存储它们(并且还有采用引用的比较运算符,qSort 不会找到你的指针比较函数),或者传递第三个带有您定义的函数的参数。
可能需要用例子来解释为什么会这样。
LogEvent event1, event2;
LogEvent *eventptr1=&event1,*eventptr2=&event2;
event1<event2; // Operator not defined in your code
event1<eventptr2; // This will call the operator you have defined
eventptr1<eventptr2; // This will compare the pointers themselves, not the LogEvents. The pointers are not dereferenced here.
预计到达时间:为了接受一个完整的答案,我将从这里的其他答案中摘取一些好的部分。
首先,定义一个小于操作符的标准语法:
class LogEvent : public QTreeWidgetItem {
public:
// ...
bool operator<(const LogEvent *); // Non-standard, possibly reasonable for use in your own code.
bool operator<(const LogEvent &); // Standard, will be used by most template algorithms.
// ...
}
日志事件.cpp
bool LogEvent::operator<(const LogEvent &event) {return timestamp<event.timestamp;}
完成此操作后,您可以使用来自 leemes 的答案的此模板取消引用和比较:
template<class T>
bool dereferencedLessThan(T * o1, T * o2) {
return *o1 < *o2;
}
像这样对你的列表进行排序:
QVector<LogEvent *> currentItems;
//add a bunch of LogEvent objects to currentItems
qSort(list.begin(), list.end(), dereferencedLessThan<LogEvent>);
为了完整起见,最好为所有比较定义标准语法比较运算符。是否保留非标准比较运算符取决于您。
关于c++ - 使用 qSort 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8186478/