对由两个数组组成的结构进行排序

Sort a structure which consists of two arrays

本文关键字:结构 排序 数组 两个      更新时间:2023-10-16

我有一个结构,看起来像这样:

struct MyStruct {
    int a[9];
    int index[9];
}

我希望根据数组'a'的值对这个结构进行排序,并使数组'index'的相应值自动调整为相同的值。

请指导我如何为这样的结构编写比较函数。

EDIT:我想通过传递此结构并使用自定义比较函数根据数组'a'的值对结构进行排序,使用内置排序函数(如qsortsort)对这样的结构进行排序。这将帮助我学习如何使用这样的比较函数,因此具体的要求。

问题是sort使用swap重新排列顺序和交换地址以交换指向用于排序的数据。a of type int& .

所以这是一个解决方案:

#include <iostream>
#include <iterator>
#include <algorithm>
static_assert(__cplusplus >= 201103L, "not C++11");
using std::cout;
using std::endl;
class OhMy {
public:
    int a[9];
    int index[9];
    OhMy() {
        int i = 9;
        for (int& b : a)
            b = i--;
        i = 19;
        for (int& b : index)
            b = i--;
    }
    template <class T>
    void swap(T& i,T& j) {
        std::swap(i,j);
        // dirty pointer arithmetic
        std::swap(index[std::distance(&a[0],&i)],index[std::distance(&a[0],&j)]);
    }
    void sort() {
        std::sort(std::begin(a),std::end(a));
    }
    void dump() {
        copy(std::begin(a),std::end(a), std::ostream_iterator<int>(std::cout, " "));
        cout << endl;
        copy(std::begin(index),std::end(index), std::ostream_iterator<int>(std::cout, " "));
        cout << endl;
    }
};
int main() {
    OhMy ohMy;
    cout << "Before:";
    ohMy.dump();
    cout << "swap:";
    ohMy.swap(ohMy.a[0],ohMy.a[1]);
    ohMy.dump();
    cout << "After sort:";
    ohMy.sort();
    ohMy.dump();
    return 0;
}

它有效!不! !

Before:9 8 7 6 5 4 3 2 1
19 18 17 16 15 14 13 12 11
交换:8 9 7 6 5 4 3 2 1
18 19 17 16 15 14 13 12 11
后排序:1 2 3 4 5 6 7 8 9
18 19 17 16 15 14 13 12 11

因此sort使用std::swapstd::swap_iter而不是本地可见的swap

你必须自己排序,因为我所知道的所有排序都只接受cmp而不是swap作为参数。