How do I reverse a C++ vector?

后端 未结 6 782
眼角桃花
眼角桃花 2020-12-07 17:05

Is there a built-in vector function in C++ to reverse a vector in place?

Or do you just have to do it manually?

相关标签:
6条回答
  • 2020-12-07 17:35

    There's a function std::reverse in the algorithm header for this purpose.

    #include <vector>
    #include <algorithm>
    
    int main() {
      std::vector<int> a;
      std::reverse(a.begin(), a.end());
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-07 17:42

    All containers offer a reversed view of their content with rbegin() and rend(). These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.

    #include <vector>
    #include <iostream>
    
    template<class InIt>
    void print_range(InIt first, InIt last, char const* delim = "\n"){
      --last;
      for(; first != last; ++first){
        std::cout << *first << delim;
      }
      std::cout << *first;
    }
    
    int main(){
      int a[] = { 1, 2, 3, 4, 5 };
      std::vector<int> v(a, a+5);
      print_range(v.begin(), v.end(), "->");
      std::cout << "\n=============\n";
      print_range(v.rbegin(), v.rend(), "<-");
    }
    

    Live example on Ideone. Output:

    1->2->3->4->5
    =============
    5<-4<-3<-2<-1
    
    0 讨论(0)
  • 2020-12-07 17:44

    Often the reason you want to reverse the vector is because you fill it by pushing all the items on at the end but were actually receiving them in reverse order. In that case you can reverse the container as you go by using a deque instead and pushing them directly on the front. (Or you could insert the items at the front with vector::insert() instead, but that would be slow when there are lots of items because it has to shuffle all the other items along for every insertion.) So as opposed to:

    std::vector<int> foo;
    int nextItem;
    while (getNext(nextItem)) {
        foo.push_back(nextItem);
    }
    std::reverse(foo.begin(), foo.end());
    

    You can instead do:

    std::deque<int> foo;
    int nextItem;
    while (getNext(nextItem)) {
        foo.push_front(nextItem);
    }
    // No reverse needed - already in correct order
    
    0 讨论(0)
  • 2020-12-07 17:48

    You can also use std::list instead of std::vector. list has a built-in function list::reverse for reversing elements.

    0 讨论(0)
  • 2020-12-07 17:53

    You can use std::reverse like this

    std::reverse(str.begin(), str.end());
    
    0 讨论(0)
  • 2020-12-07 18:00
    #include<algorithm>
    #include<vector>
    #include<iostream>
    using namespace std;
    int main()
    {
        vector<int>v1;
        for(int i=0; i<5; i++)
            v1.push_back(i*2);
        for(int i=0; i<v1.size(); i++)
            cout<<v1[i];    //02468
        reverse(v1.begin(),v1.end());
        
        for(int i=0; i<v1.size(); i++)
            cout<<v1[i];   //86420
    }
    
    0 讨论(0)
提交回复
热议问题