使用 C++ 中的 STL pair 根据另一个数组对数组进行排序


假设我们有两个不同的数组。我们必须使用 C++ STL pair 类根据另一个数组对一个数组进行排序。考虑两个数组,例如 A1 = [2, 1, 5, 4, 9, 3, 6, 7, 10, 8],另一个数组为 A2 = [A, B, C, D, E, F, G, H, I, J],输出将如下所示:A1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],A2 = [B, A, F, D, C, G, H, J, E, I]

在这里,我们正在使用 C++ STL 的对。一对是通过从 A1 中取一个元素,从 A2 中取另一个元素来形成的。然后只需使用排序函数。我们考虑的一件事是该对中的第一个元素应该形成数组,根据该数组执行排序。

示例

 在线示例

#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
template <class T>
void display(T arr[], int n) {
   for (int i = 0; i < n; i++)
   cout << arr[i] << " ";
}
void sortUsingSecondArr(int A1[], char A2[], int n){
   pair<int, char> pair_arr[n];
   for (int i = 0; i < n; i++) {
      pair_arr[i].first = A1[i];
      pair_arr[i].second = A2[i];
   }
   sort(pair_arr, pair_arr + n);
   for (int i = 0; i < n; i++) {
      A1[i] = pair_arr[i].first;
      A2[i] = pair_arr[i].second;
   }
}
int main() {
   int n = 10;
   int A1[] = {2, 1, 5, 4, 9, 3, 6, 7, 10, 8};
   char A2[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
   cout << "Before Sorting: "<<endl;
   cout << "First Array : "; display(A1, n);
   cout << "\nSecond Array: "; display(A2, n);
   sortUsingSecondArr(A1, A2, n);
   cout << "\n\nAfter Sorting: "<<endl;
   cout << "First Array : "; display(A1, n);
   cout << "\nSecond Array: "; display(A2, n);
}

输出

Before Sorting:
First Array : 2 1 5 4 9 3 6 7 10 8
Second Array: A B C D E F G H I J
After Sorting:
First Array : 1 2 3 4 5 6 7 8 9 10
Second Array: B A F D C G H J E I

更新于:2019 年 10 月 21 日

759 浏览次数

开启你的 职业生涯

完成课程,获得认证

开始吧
广告
© . All rights reserved.