std::sort with QObject 和 QVector<MyQObject*>



我对QVector<MyQObject*>。这是用于列出目录和数据的真实情况(如ls-unix命令(。在这个例子中/用户/Stehane/";在我的unix macos计算机上。

std::sort函数不起作用,我确信我犯了一个错误。

以下是我的控制台Qt:文件

entry.h

#ifndef ENTRY_H
#define ENTRY_H
#include <QObject>
#include <QString>
#include <QDateTime>
enum Type {
File, Directory, Other
};

class Entry : public QObject
{
Q_OBJECT
public:
explicit Entry(QObject *parent = nullptr);
void setValue(Type type, QString name, int size_file);
QString getName();
int getSize();
bool operator<(const Entry other);
signals:
private:
QString name;
Type type;
int size_file;
};
#endif // ENTRY_H

entry.cpp

#include "entry.h"
Entry::Entry(QObject *parent)
: QObject{parent}
{
}
void Entry::setValue(Type type, QString name, int size_file)
{
this->type = type;
this->name = name;
this->size_file = size_file;
}
QString Entry::getName()
{
return this->name;
}
int Entry::getSize() {
return this->size_file;
}
bool Entry::operator<(const Entry other) {
return this->name < other.name;
}

main.cpp

#include <QCoreApplication>
#include "entry.h"
#include <sys/stat.h>
#include <dirent.h>
#include <QDebug>
#include <iostream>
#include <QDateTime>
struct EntryCompare {
bool operator()(const Entry *a, const Entry *b) {
return(a < b);
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// My vector
QVector<Entry*> vec_entry;
QString directory = "/Users/Stephane/";
// Read dir/file
struct dirent *lecture;
DIR *dir;
struct stat buf;
QString currentPath;
dir = opendir(directory.toLocal8Bit());
if (dir == NULL) {
qCritical() << directory << " don't exist";
return a.exec();
}
while ((lecture = readdir(dir)) != NULL) {
if (strcmp(lecture->d_name, ".") != 0) {
currentPath = directory + lecture->d_name;
const char *charCurrentPath = currentPath.toLocal8Bit();
if ((stat(charCurrentPath, &buf)) == -1) {
qCritical() << "stat" << currentPath;
}
int size = buf.st_size;
Entry *entry = new Entry();
if (!strcmp(lecture->d_name, "..")) {
entry->setValue(Type::Directory, lecture->d_name, 0);
vec_entry.append(entry);
} else {
vec_entry.append(entry);
if (S_ISDIR(buf.st_mode)) {
QString qstringTemp = lecture->d_name;
qstringTemp += "/";
entry->setValue(Type::Directory, qstringTemp, 0);
} else {
entry->setValue(Type::File, lecture->d_name, size);
}
}
}
}
closedir(dir);
// This part doesn't work
std::sort(vec_entry.begin(), vec_entry.end(), EntryCompare());
foreach(Entry *v, vec_entry) {
qInfo() << "Vector entry:" << v << "Name:" << v->getName() << "Size:" << v->getSize();
}
return a.exec();
}

当您将指针传递给任何函数时,您有责任取消引用指针并从中获取它所指向的信息。这不是自动的,您必须编写代码才能完成。

对于CCD_ 1";不工作";,它和你写的一模一样。您的比较规范正在比较两个指针的值。您负责提供std::sort

  1. 要排序的正确范围,加上
  2. 对两个值进行排序的正确排序标准,加上
  3. 排序标准遵循";严格弱排序";(在哪个项目放在另一个项目之前没有歧义(

如果这样做,std::sort会一直工作。如果结果是错误的,那么您一定违反了其中的一个或多个先决条件。你的代码违反了数字2(。

很可能,你打算做以下事情:

struct EntryCompare 
{
bool operator()(Entry *a, Entry *b) const
{
return(a->getName() < b->getName());
}
};

这将比较ab指向的名称。

最新更新