常用C++ algorithm: reverse

  • 【用途】將指定區間內的陣列(or vector)元素順序反轉。
  • 【範例】
    • v = [ 0 1 2 3 4 5 6 7 8 9 ]
    • reverse(v.begin(), v.end()); 之後
    • v = [ 9 8 7 6 5 4 3 2 1 0 ]
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    vector <int> v;
    for (int i=0; i<10; i++){
        v.push_back(i);
    }
    
    for (auto i: v) cout << i << ' ';
    cout << endl;
    
    reverse(v.begin(), v.end());
    
    for (auto i: v) cout << i << ' ';
    cout << endl;
    
    return 0;
}

分享本文 Share with friends