sort one array and other array following?

后端 未结 3 708
北海茫月
北海茫月 2021-01-28 23:28

here is the C++ sample

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

how do i make it so if i sort array a, array b also following array a

相关标签:
3条回答
  • 2021-01-28 23:57

    The simplest way is to rearrange your data into an array-of-structs instead of a pair of arrays so that each datum is contiguous; then, you can use an appropriate comparator. For example:

    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());
    

    If you can't refactor your data like that, then you need to define a custom class that acts as a 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));
    
    0 讨论(0)
  • 2021-01-29 00:02

    Generate an array the same size as the original, containing the indexes into the array: {0, 1, 2, 3}. Now use a custom comparator functor that compares the elements in an associated array rather than the indexes themselves.

    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));
    

    Once you have a sorted list of indices, you can apply it to the original array a, or any other b array you want.

    0 讨论(0)
  • 2021-01-29 00:03

    Instead of using two arrays, can you use an array of pairs and then sort THAT using a special comparison functor rather than the default less-than operator?

    0 讨论(0)
提交回复
热议问题