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?
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?
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: