How do I reverse a C++ vector?

后端 未结 6 781
眼角桃花
眼角桃花 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: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 
    #include 
    
    template
    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 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
    

提交回复
热议问题