There's a function std::reverse in the algorithm header for this purpose.
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
Answer from Ivaylo Strandjev on Stack OverflowThere's a function std::reverse in the algorithm header for this purpose.
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
All containers offer a reversed view of their content with rbegin() and rend(). These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.
#include <vector>
#include <iostream>
template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "\n"){
--last;
for(; first != last; ++first){
std::cout << *first << delim;
}
std::cout << *first;
}
int main(){
int a[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(a, a+5);
print_range(v.begin(), v.end(), "->");
std::cout << "\n=============\n";
print_range(v.rbegin(), v.rend(), "<-");
}
Live example on Ideone. Output:
1->2->3->4->5
=============
5<-4<-3<-2<-1
c++ please 20 LAB: Reverse vector plete Reverse() function that returns a new character vector containing all contents in the input argument reversed. f the input vector is: a', 'b', 'c'] n the returned vector will be: 'c', 'b', 'a'] 70.1771362.qx3zqy7 LAB ACTIVITY 4.20.1: LAB: Reverse vector 1 #include 2 #include 3 using namespace std; 4 5 // This method
Proper way to do backward iteration in C++
Reverse Iteration in C++ STL
Vectors-- reversing an array - C++ Forum
Videos
Suppose we have some vector<T> data, and wanna iterate it backwards maintaining the index. We all know the struggle, can't just write
for (size_t i = data.size() - 1; i >= 0; --i)
So there are multiple ways to deal with it, all are equally bad. For a example
for (ssize_t i = static_cast<ssize_t>(data.size()) - 1; i >= 0; --i)
which doesn't work if data.size() > SSIZE_MAX.
Or there is something like
for (size_t rev_i = 0; rev_i < data.size(); ++rev_i) {
size_t i = data.size() - rev_i - 1;
}Do we really need two variables to perform such a complex action? Hopefully, there is a way. Just do
for (size_t i = data.size() - 1; i < data.size(); --i)
which works with any data.size() and more importantly shows your superior c++ coding skills. Also be ready to be praised by your colleagues for writing readable code.
In the below program I am trying to delete the first iteration of lowercase alphabet. And so I am getting error for deleting (*itt) . What could be possible solution.
for(auto itt=vec2.rbegin();itt!=vec2.rend();){
if(islower(*itt)){
itt= vec2.erase(itt);//error in this line
break;
}else{
itt++;
}
}