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

时光总嘲笑我的痴心妄想 提交于 2019-12-22 13:56:24

问题


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


来源:https://stackoverflow.com/questions/11019722/how-to-reverse-a-vector-of-strings-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!