C ++在新数组中排序索引

时间:2016-02-15 20:36:06

标签: c++

我们说我有一个数组A = {6.5,2.2,5.6,7.1}。如何在不更改A的​​原始内容的情况下将数组的有序索引放在新数组中?所以,B等于{1,2,0,3}。

编辑:我当前的代码只是命令原始数组本身。

int main(){
    int temp;
    const int N = 6;
    int arr[N] = {6.5, 2.2, 5.6, 7.1};
    int sortedIndex[N];
    for (int i = 0; i < N; i++){
         for (int j = i + 1; j < N; j++){
             if (arr[j] < arr[i]){
                 temp = arr[i]
                 arr[i] = arr[j]
                 arr[j] = temp; }
    {
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您可以使用自定义比较器执行此操作:

std::array<double, 4> A = {6.5, 2.2, 5.6, 7.1};

std::array<int,4> indices;
std::iota(begin(indices), end(indices), 0); // initialize the index array

// sort with custom comparator, that compares items not by their own value
// but by the value of the corresponding entries in the original array.
std::sort(begin(indices), end(indices),
          [&A](int lhs, int rhs) { return A[lhs] < A[rhs]; });

std::copy(begin(indices), end(indices), std::ostream_iterator<int>(std::cout, " "));