C++ vector::rbegin() Function
The C++ vector::rbegin() function is used to return the reverse iterator pointing to the vector's final element. A reverse iterator iterates backward, and increase in its result, advances the vector container to the beginning. Similar reducing a reverse iterator causes the vector container to move to the end. The time complexity of the rbegin() function is constant.
In contrast to the back() function, which returns a direct reference to the last element, this function returns the reverse iterator pointing to the same element of the vector.
Syntax
Following is the syntax for C++ vector::rbegin() Function −
reverse_iterator rbegin() noexcept;const_reverse_iterator rbegin() const noexcept;
Parameters
It doesn't contains any kind of parameters.
Example 1
Let's consider the following example, where we are going to use the rbegin() function.
#include <iostream>
#include <vector>
using namespace std;
int main(void){
vector<int> v = {1, 2, 3, 4, 5};
for (auto it = v.rbegin(); it != v.rend(); ++it)
cout << *it << endl;
return 0;
}
Output
When we compile and run the above program, this will produce the following result −
5 4 3 2 1
Example 2
Considering the another scenario, where we are going to take the char type.
#include <iostream>
#include<vector>
using namespace std;
int main(){
vector<char> myvector{'T','L','E','Z','U','R','C'};
vector<char>::reverse_iterator x;
for(x=myvector.rbegin(); x!=myvector.rend(); x++)
std::cout<< *x;
return 0;
}
Output
On running the above program, it will produce the following result −
CRUZELT
Example 3
In the following example, we are going to use the push_back() function to insert the elements and getting the last element of the vector.
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> myvector;
myvector.push_back(22);
myvector.push_back(44);
myvector.push_back(6);
myvector.push_back(8);
vector<int>::reverse_iterator x;
x = myvector.rbegin();
cout << "Last Element Is : " << *x << endl;
return 0;
}
Output
When we execute the above program, it will produce the following result −
Last Element Is : 8
Example 4
Following is the example, where we are going to take the string typr and applying the rbegin() function.
#include <iostream>
#include <vector>
using namespace std;
int main (){
vector<string> foodchain{"Tiger","Cow ->","Tree ->"};
vector<string>::reverse_iterator x;
x = foodchain.rbegin();
cout<<*x<<" ";
x++;
cout<<*x<<" ";
x++;
cout<<*x<<" ";
return 0;
}
Output
On running the above program, it will produce the following result −
Tree -> Cow -> Tiger