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

การกลับลำดับ Vector ด้วย STL ใน C++

การกลับลำดับ Vector (Reverse Vector) ด้วย STL ใน C++

ใช้ std::reverse จาก <algorithm> กลับลำดับองค์ประกอบใน vector

ตัวอย่าง

#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;
    
    // กลับลำดับ
    reverse(a.begin(), a.end());
    
    cout << "Reversed Vector: ";
    for (int i = 0; i < a.size(); i++) cout << a[i] << " ";
    cout << endl;
    return 0;
}

ผลลัพธ์

Vector: 1 45 54 71 76 12
Reversed Vector: 12 76 71 54 45 1

คำอธิบาย

  • reverse(begin, end) กลับลำดับในช่วง [begin, end) แบบ in-place
  • Complexity: O(n) swaps
  • ใช้ได้กับ container ใดๆ ที่มี bidirectional iterators (vector, deque, list, array, string)

ฟังก์ชันที่เกี่ยวข้อง

  • reverse_copy - คัดลอกพร้อมกลับลำดับ (ไม่เปลี่ยนต้นฉบับ)
  • std::ranges::reverse (C++20) - ใช้แบบ range-based