REVERSE()
This function reverses the order of elements within a specified range, typically defined by a container’s begin()
and end()
iterators. This function operates in place, meaning it modifies the original container without creating a copy. It requires bidirectional iterators, making it compatible with containers like std::vector
, std::list
, and arrays but not std::forward_list
. std::reverse()
is efficient and easy to use, offering a quick way to flip the order of characters in a string or elements in a container without writing a manual loop. To reverse strings specifically, the <string>
header is also commonly included. Additionally, you can reverse only a portion of a container by specifying a custom range using iterators, such as specific start and end positions.
//SYNTAX
reverse(startIterator, endIterator);
// Reverses elements from startIterator up to (but not including) endIterator
// Example: Partial reverse (first 5 characters)
reverse(str.begin(), str.begin() + 5);
// Example: Reverse from 3rd position to end
reverse(str.begin() + 2, str.end());
#include <iostream> // For input and output
#include <string> //required when manipulating string objects
#include <algorithm> // For reverse()
using namespace std;
int main() {
string text = "codechef"; // Original string
reverse(text.begin(), text.end()); // Reverse the string
cout << "Reversed Text: " << text << endl; // Display result
return 0; // End of program
}
OUTPUT:
Reversed Text: fehcedoc
Last updated