c++ - 对两个对应的数组进行排序

我这里有这段代码,它有两个数组。它对 arr[] 进行排序,因此最高值将位于索引 0 中。现在第二个数组 arr1[] 包含字符串,我希望代码应用任何内容将 arr[] 更改为 arr1[]。这样 arr[0] 将返回 6,而 arr1[0] 将返回字符串 "d1"。注意 "d1" 如何与 6 处于同一索引中?排序后,我希望相同的值仍然具有对应的字符串。

我该怎么做呢?

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <functional>
using namespace std;

int main() {
  int arr[ 5 ] = { 4, 1, 3, 6, 2 };  
  string arr1[ 5 ] = { "a1", "b1", "c1", "d1", "e1" };

  std::sort( arr, arr + 5, std::greater< int >() );
  cout << arr[0] << arr1[0] << endl;

  system("pause");
}

最佳答案

不是对数组进行排序,而是对索引进行排序。也就是说,你有

int arr[5]={4,1,3,6,2}
string arr1[5]={"a1","b1","c1","d1","e1"};

你做

int indices[5]={0,1,2,3,4};

现在您制作了一个看起来像这样的排序索引比较器(只是想法,您可能需要稍微修复一下)

class sort_indices
{
   private:
     int* mparr;
   public:
     sort_indices(int* parr) : mparr(parr) {}
     bool operator()(int i, int j) const { return mparr[i]<mparr[j]; }
}

现在你可以使用 STL 排序了

std::sort(indices, indices+5, sort_indices(arr));

完成后,索引数组将使得 arr[indices[0]] 是第一个元素。同样 arr1[indices[0]] 是对应的对。

当您尝试对大型数据对象进行排序时,这也是一个非常有用的技巧,您不需要在每次交换时移动数据,只需移动索引即可。

https://stackoverflow.com/questions/3909272/

相关文章:

c++ - Visual Studio 可以在重建前提示吗?

c++ - 如何检查 STL 迭代器是否指向任何东西?

c++ - 类成员和显式堆栈/堆分配

c++ - 如何在互斥锁中优先考虑特权线程?

c++ - 条件变量 - 为什么在调用 pthread_cond_wait() 之前调用 pthre

c++ - 如何在编译时检查两种类型是否相同(如果它与 Boost strong typedef 一

c++ - 有没有办法在 Visual Studio 中获取某些 c++ 函数的调用图?

c++ - 定义一个结尾没有空终止字符(\0)的字符串

c++ - #include 在查找预编译头文件时跳过 -- 查找预编译头文件时文件意外结束

c++ - 如何以跨平台的方式获取(几乎)唯一的系统标识符?