How to reverse a vector of strings in C++?
本问题已经有最佳答案,请猛点这里访问。
我有一个字符串向量,我想反转向量并打印它,或者简单地说,以相反的顺序打印向量。我该怎么做呢?
如果要以相反的顺序打印矢量:
1
2 3 4 5 6 7 8 9 |
#include #include <iterator> #include <iostream> #include <vector> #include <string> std::copy(v.rbegin(), v.rend(), |
如果要反转向量,然后打印:
1
2 3 4 |
std::reverse(v.begin(), v.end());
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout,"/ ")); |
如果要创建矢量的反向副本并打印:
1
2 3 4 |
std::vector<std::string> r(v.rbegin(), v.rend());
std::copy(r.begin(), r.end(), std::ostream_iterator<std::string>(std::cout,"/ ")); |
最后,如果您更喜欢编写自己的循环而不是使用
1
2 3 4 5 6 |
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) <<""; } } |
或者,
1
2 3 4 5 6 7 |
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) <<""; } } |
参考文献:
- 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
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/268720.html