c++ - 使用 Qt/C++ 的排序算法 - 对结构的 QList 进行排序

标签 c++ algorithm qt sorting

我想知道它们是否是 STL 或 Qt 中的某种算法,用于对 double 数组进行排序并返回原始列表中已排序项的索引。 例如。大号 = 1 , 2 , 5 , 3 L_sort = 1 , 2 , 3 , 5 指数 = 1, 2, 4, 3

这样我之后就可以计算 AnotherList[Indices](相对于原始列表 L,两个列表中的顺序相同)。

最后,我想到了创建一个QList,每个MyStruct 包含两个成员,一个是与L 中的元素相同类型的LType,另一个是与AnotherList 中的元素相同类型的AnotherType。然后根据 LType 类型的成员进行排序。但是我有这个想法,我不知道如何在 Qt 中进行。

感谢和问候

最佳答案

您可以成对存储带有索引的数据... 首先按值排序,然后按索引排序...

QList<QPair<LType,int> > array;
for (int i = 0; i < 100; i++)
{
    LType x = ...
    array.append(qMakePair(x,i));
}

// Ordering ascending
qSort(array.begin(), array.end(), QPairFirstComparer());

.....

// Restoring start order
qSort(array.begin(), array.end(), QPairSecondComparer());

你只需要这些类:

struct QPairFirstComparer
{
    template<typename T1, typename T2>
    bool operator()(const QPair<T1,T2> & a, const QPair<T1,T2> & b) const
    {
        return a.first < b.first;
    }
};

struct QPairSecondComparer
{
    template<typename T1, typename T2>
    bool operator()(const QPair<T1,T2> & a, const QPair<T1,T2> & b) const
    {
        return a.second < b.second;
    }
};

关于c++ - 使用 Qt/C++ 的排序算法 - 对结构的 QList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10188920/

相关文章:

c++ - Go和C++中指针和引用之间的逻辑区别?

C++11 正则表达式和字符串 u8 前缀

c++ - 冒泡排序优化 C++

C++/Qt : how to access windows registry remotely?

c++ - 使用 ffmpeg.dll 或 avcodec.dll 将视频文件转换为 TIFF? "on-the-fly"可能吗?

c++ - Abaqus C++ API 语法

c# - 计算围绕一条线的长方体的 Point3Ds

c# - 如何在不使用 math.pow 的情况下分解 x^(x+1)

java - 如何在 java 中交换 int 的位置?

c++ - Qt 与 Dlib 和 CUDA