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

การจัดเรียง Vector ใน C++

การจัดเรียง Vector ใน C++ ทำได้ด้วย std::sort() ใน <algorithm> สำหรับ Stable Sort ใช้ std::stable_sort รักษาลำดับสัมพัทธ์ของสมาชิกเท่ากัน

อัลกอริทึม

Begin
    Declare vector v with values
    Print "Elements before sorting"
    Print all elements
    Print "Elements after sorting"
    Call sort(v.begin(), v.end()) for ascending
    Print all elements
End.

ตัวอย่าง

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {10, 9, 8, 6, 7, 2, 5, 1};
    cout << "Elements before sorting" << endl;
    for (const auto &i : v) cout << i << ' ' << endl;
    cout << "Elements after sorting" << endl;
    sort(v.begin(), v.end());
    for (const auto &i : v) cout << i << ' ' << endl;
    return 0;
}

ผลลัพธ์

Elements before sorting
10 9 8 6 7 2 5 1
Elements after sorting
1 2 5 6 7 8 9 10