首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对一个数组和后面的其他数组进行排序?

对一个数组和后面的其他数组进行排序?
EN

Stack Overflow用户
提问于 2011-09-05 11:06:28
回答 3查看 924关注 0票数 0

下面是C++示例

代码语言:javascript
复制
int a[1000] = {3,1,5,4}
int b[1000] = {7,9,11,3}

如果我对数组a排序,数组b也跟在数组a之后,我该怎么做呢?

示例

代码语言:javascript
复制
a[1000] = {1,3,4,5}
b[1000] = {9,7,3,11}

是否可以使用排序函数

代码语言:javascript
复制
sort(a,a+4)

还能排序数组b吗?

编辑:如果有3个数组怎么办?

EN

回答 3

Stack Overflow用户

发布于 2011-09-05 11:37:21

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

票数 1
EN

Stack Overflow用户

发布于 2011-09-05 11:43:47

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

代码语言:javascript
复制
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的自定义类

代码语言:javascript
复制
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));
票数 0
EN

Stack Overflow用户

发布于 2011-09-05 12:03:17

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

代码语言:javascript
复制
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数组。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7303572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档