我这里有这段代码,它有两个数组。它对 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/