Reverse function in C++
The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need to import the algorithm statement.
- Example of reverse function using vector standard template library.
#include <vector>
#include <iostream>
// The following header needs to be included to use std::reverse()
#include <algorithm>
using namespace std;
int main() {
std::vector<int> values = {
3,4,6,2,4,7,3,6,3,6,3,6,98
};
std::cout << "Before reversing: ";
for(int x: values) {
std::cout << x << ' ';
}
std::reverse(values.begin(), values.end());
std::cout << "\nAfter reversing: ";
for(int x: values) {
std::cout << x << ' ';
}
}
Output:
Explanation:
In the above code, we have declared a vector data type in which we have given some data. To use the reverse function, we have imported the algorithm library. We reversed the vector data using the reverse function and printed the output.
- Example of Reverse function for the array
#include <iostream>
// The following header needs to be included to use std::reverse()
#include <algorithm>
// The following header needs to be included to use std::begin() and std::end()
#include <iterator>
using namespace std;
int main() {
int arr[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
std::cout << "Before reversing: ";
for(int x: arr) {
std::cout << x << ' ';
}
// built-in array has no begin() and end() member functions
// but we can pass it to std::begin() and std::end()
// in order to get the iterators we need
std::reverse(std::begin(arr), std::end(arr));
std::cout << "\nAfter reversing: ";
for(int x: arr) {
std::cout << x << ' ';
}
}
Output:
Explanation
In this example, we have used the reverse function to reverse the array. To use the reverse function, we have imported the algorithm library. For the parameters, we have used functions present in the iterator library to send the starting and ending values of the array and then printed the reverse of the array.
- Example of reverse function for a string
#include <string>
#include <iostream>
// The following header needs to be included to use std::reverse()
#include <algorithm>
using namespace std;
int main() {
std::string sentence = "Hello, World!";
std::cout << "Before reversing: " << sentence << '\n';
std::reverse(sentence.begin(), sentence.end());
std::cout << "After reversing: " << sentence << '\n';
}
Output:
Explanation:
In the above example, we have used the reverse function to reverse a string. To use the reverse function, we have imported the algorithm library. Using the reverse statement, we have reversed the string by passing starting and ending character of the string .