【问题标题】:sort one array and other array following?对一个数组和另一个数组进行排序?
【发布时间】:2011-09-05 03:06:28
【问题描述】:

这里是 C++ 示例

int a[1000] = {3,1,5,4}
int b[1000] = {7,9,11,3}

如果我对数组 a 进行排序,数组 b 也在数组 a 之后,我该如何做到这一点

例子

a[1000] = {1,3,4,5}
b[1000] = {9,7,3,11}

是否可以使用排序功能

sort(a,a+4)

还能对数组 b 进行排序吗?

编辑:如果有 3 个数组呢?

【问题讨论】:

  • 您使用索引进行排序。见stackoverflow.com/questions/1577475/…
  • @ben 因为 b 没有排序。它以与 a was 相同的方式重新排列。
  • 啊哈。那么zuelb应该写自己的排序函数。

标签: c++ arrays sorting


【解决方案1】:

您可以使用pairs 的数组而不是使用两个数组,然后使用特殊的比较函子而不是默认的小于运算符对其进行排序吗?

【讨论】:

  • 如果有3个数组,可以用这个方法吗?
  • 好吧,在这种情况下你需要一个 3 元组(或者为它自己写一个结构体),但基本上,可以。
【解决方案2】:

最简单的方法是将数据重新排列成一个结构数组而不是一对数组,这样每个数据都是连续的;然后,您可以使用适当的比较器。例如:

struct CompareFirst
{
    bool operator() (const std::pair<int,int>& lhs, const std::pair<int,int>& rhs)
    {
        return lhs.first < rhs.first;
    }
};

// c[i].first contains a[i], c[i].second contains b[i] for all i
std::pair<int, int> c[1000];
std::sort(c, c+1000, CompareFirst());

如果你不能像那样重构你的数据,那么你需要定义一个自定义类来充当RandomAccessIterator

struct ParallalArraySortHelper
{
    ParallelArraySortHelper(int *first, int *second)
        : a(first), b(second)
    {
    }

    int& operator[] (int index) { return a[index]; }
    int operator[] const (int index) { return a[index]; }

    ParallelArraySortHelper operator += (int distance)
    {
        a += distance;
        b += distance;
        return *this;
    }
    // etc.
    // Rest of the RandomAccessIterator requirements left as an exercise

    int *a;
    int *b;
};
...
int a[1000] = {...};
int b[1000] = {...};
std::sort(ParallalArraySortHelper(a, b), ParallelArraySortHelper(a+1000, b+1000));

【讨论】:

    【解决方案3】:

    生成一个与原始大小相同的数组,其中包含数组的索引:{0, 1, 2, 3}。现在使用自定义比较器函子来比较关联数组中的元素而不是索引本身。

    template<typename T>
    class CompareIndices
    {
    public:
        CompareIndices(const T * array) : m_AssociatedArray(array) {}
        bool operator() (int left, int right) const
        {
            return std::less(m_AssociatedArray[left], m_AssociatedArray[right]);
        }
    private:
        const T * m_AssociatedArray;
    };
    
    std::sort(i, i+4, CompareIndices(a));
    

    一旦你有一个排序的索引列表,你可以将它应用到原始数组a,或者你想要的任何其他b数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 2017-04-27
      • 2020-03-19
      • 1970-01-01
      • 2013-11-10
      相关资源
      最近更新 更多