Sắp xếp mảng A1 dựa trên thứ tự của mảng A2 dùng std::pair trong C++ STL. Ví dụ A1 = [2, 1, 5, 4, 9, 3, 6, 7, 10, 8], A2 = [A, B, C, D, E, F, G, H, I, J]. Kết quả: A1 sắp xếp tăng, A2 theo thứ tự tương ứng [B, A, F, D, C, G, H, J, E, I].
Tạo mảng pair<int, char> từ hai mảng, sort theo first (A1), sau đó tách ra lại.
Ví dụ
#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);
}
Kết quả
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