sort one array and other array following?

后端 未结 3 717
北海茫月
北海茫月 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-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
    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.

提交回复
热议问题