Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Sorting Array ตามอีก Array ด้วย Pair ใน STL C++

สมมติมี 2 Arrays ต้องการ Sort Array หนึ่งตามอีก Array ด้วย C++ STL Pair Class ตัวอย่าง A1=[2,1,5,4,9,3,6,7,10,8] A2=[A,B,C,D,E,F,G,H,I,J] Output: A1=[1,2,3,4,5,6,7,8,9,10] A2=[B,A,F,D,C,G,H,J,E,I]

ใช้ Pair ของ STL: Pair ประกอบด้วย Element จาก A1 และ A2 แล้ว Sort ธรรมดา สำคัญคือ First Element ใน Pair ต้องเป็น Array ที่ใช้ Sort

ตัวอย่างโค้ด C++

#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