下面是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个数组怎么办?
发布于 2011-09-05 11:37:21
是否可以使用一个pair数组,然后使用特殊的比较函数而不是默认的小于运算符对其进行排序,而不是使用两个数组?
发布于 2011-09-05 11:43:47
最简单的方法是将数据重新排列到一个结构数组中,而不是一对数组中,这样每个数据都是连续的;然后,您可以使用适当的比较器。例如:
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));发布于 2011-09-05 12:03:17
生成一个与原始数组大小相同的数组,其中包含数组中的索引:{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数组。
https://stackoverflow.com/questions/7303572
复制相似问题