Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Sắp xếp Vector giảm dần bằng STL trong C++


Trong hướng dẫn này, chúng ta sẽ thảo luận về cách sắp xếp vector theo thứ tự giảm dần sử dụng STL trong C++.

Để sắp xếp vector giảm dần, ta dùng hàm sort() từ thư viện STL với đối số so sánh greater<int>().

Ví dụ

#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> a = { 1, 45, 54, 71, 76, 12 };
    cout << "Vector: ";
    for (int i = 0; i < a.size(); i++) cout << a[i] << " ";
    cout << endl;
    // sắp xếp giảm dần
    sort(a.begin(), a.end(), greater<int>());
    cout << "Sorted Vector in descending order: ";
    for (int i = 0; i < a.size(); i++) cout << a[i] << " ";
    cout << endl;
    return 0;
}

Đầu ra

Vector: 1 45 54 71 76 12
Sorted Vector in descending order: 76 71 54 45 12 1