How to reverse a string in c++ using reverse function

To reverse a string in C++ using the reverse function, you need to follow these steps:

  1. Include the necessary header file: cpp #include <algorithm> This header file provides the reverse function that we will use to reverse the string.

  2. Declare and initialize a string variable: cpp std::string str = "Hello, World!"; This line declares a string variable called str and initializes it with the value "Hello, World!".

  3. Use the reverse function to reverse the string: cpp std::reverse(str.begin(), str.end()); The reverse function takes two iterators as arguments, representing the range of elements to be reversed. In this case, str.begin() represents the iterator to the beginning of the string, and str.end() represents the iterator to the end of the string. By passing these iterators to the reverse function, the string str will be reversed.

  4. Print the reversed string: cpp std::cout << str << std::endl; This line prints the reversed string (str) to the console.

Here is the complete code:

#include <iostream>
#include <algorithm>

int main() {
    std::string str = "Hello, World!";
    std::reverse(str.begin(), str.end());
    std::cout << str << std::endl;

    return 0;
}

When you run this code, it will output the reversed string: "!dlroW ,olleH".