如何根据另一个数组中每个元素的排名对数组(按升序)进行排序?

How to sort an array(in ascending order) based on the ranks of each element which is in the another array?

让两个数组

arr = [1,5,6,3,10] 


rank = [100,0,1,100,2]

基于rank数组(其中包含arr中镜像元素的ranks)结果应该是

[5,6,10,1,3]

结果中的第一个元素是5

(The index of 5 in arr is arr[1] and the index of 0 in rank is rank[1]. This is how we have to take ranks. 0 is smallest of all ranks so 5 is printed first )

结果中的第二个元素是6

The index of 6 in arr array is at the index arr[2] and its rank is 1 because that is at the index rank[2]. 1 is the second smallest of all ranks so 6 is printed next) This is how we have to sort the array based on the rank array.

Here if two ranks are same then we have to compare the values in the array itself and print the smaller first
arr[0] = 1 and arr[3] = 3 Both having same ranks 100. So compare those elements and print the smallest value. That gives the

result 5,6,10,1,3

简短的回答是:std::sort

长答案取决于您如何存储值和排名,您是否有能力复制它们,以及您是否还需要对排名进行排序。对于以下内容,我假设您不需要对排名进行排序,并且排序是在原始值容器上完成的。它不是最有效的实现,但它足够简单,可以让您入门:

#include <vector>
#include <utility>
#include <algorithm>
#include <iostream>
#include <iterator>

template <typename Iter,typename RankIter>
void rank_sort(Iter begin,Iter end,RankIter rankbegin){
    std::vector<std::pair<typename std::iterator_traits<RankIter>::value_type,
                          typename std::iterator_traits<Iter>::value_type >> res;
    for (auto beg = begin; beg != end; ++beg,++rankbegin) res.emplace_back(*rankbegin,*beg); 
    std::sort(res.begin(),res.end());
    for (const auto& e : res){
        *begin = e.second;
        ++begin;
    }
}


int main() {
    std::vector<int> arr{1,5,6,3,10};
    std::vector<int> rank{100,0,1,100,2};
    rank_sort(arr.begin(),arr.end(),rank.begin());
    for (const auto& a : arr) { std::cout << a << " ";}
}

基本思路是创建一个 std::vector<std::pair<int,int>>,然后简单地通过 std::sort 对其进行排序。其余代码是关于将值和排名复制到该向量中,并在排序后从中复制值。

如果可能,您应该首先将值和排名存储在 std::vector<std::pair<int,int>> 中。然后对它们进行排序是微不足道的。或者,如评论中所述,您可以使用排序的容器,例如 std::map.