如何在 C++ 中反转字符串向量? [英] How to reverse a vector of strings in C++?

查看:63
本文介绍了如何在 C++ 中反转字符串向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串向量,我想反转向量并打印它,或者简单地说,以相反的顺序打印向量.我该怎么做?

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?

推荐答案

如果要逆序打印矢量:

#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) << " ";
  }
}

或者,

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) << " ";
  }
} 

参考文献:

这篇关于如何在 C++ 中反转字符串向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆