How to reverse a vector of strings in C++? [duplic

2019-05-26 10:54发布

问题:

Possible Duplicate:
How to reverse a C++ vector?

I have a vector of strings and I want to reverse the vector and print it, or simply put, print the vector in reverse order. How should I go about doing that?

回答1:

If you want to print the vector in reverse order:

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
#include <string>

std::copy(v.rbegin(), v.rend(), 
  std::ostream_iterator<std::string>(std::cout, "\n"));

If you want to reverse the vector, and then print it:

std::reverse(v.begin(), v.end());
std::copy(v.begin(), v.end(),
  std::ostream_iterator<std::string>(std::cout, "\n"));

If you want to create a reversed copy of the vector and print that:

std::vector<std::string> r(v.rbegin(), v.rend());
std::copy(r.begin(), r.end(),
  std::ostream_iterator<std::string>(std::cout, "\n"));

Finally, if you prefer to write your own loops instead of using <algorithm>:

void print_vector_in_reverse(const std::vector<std::string>& v){
  int vec_size = v.size(); 
  for (int i=0; i < vec_size; i++){ 
    cout << v.at(vec_size - i - 1) << " ";
  }
}

Or,

void print_vector_in_reverse(std::vector<std::string> v) {
  std::reverse(v.begin(), v.end());
  int vec_size = v.size();
  for(int i=0; i < vec_size; i++) {
    std::cout << v.at(i) << " ";
  }
} 

References:

  • http://en.cppreference.com/w/cpp/algorithm/reverse
  • http://en.cppreference.com/w/cpp/algorithm/copy
  • http://en.cppreference.com/w/cpp/iterator/ostream_iterator
  • http://en.cppreference.com/w/cpp/container/vector/rbegin