In this blog we will learn how to reverse string in c++ using reverse function.

std::reverse() in C++ is a standard function which requires header #include<algorithm>

The syntax of std::reverse function is

void reverse(BidirectionalIterator first, BidirectionalIterator last)

how to reverse string in c++ using reverse function

#include <iostream>
#include<algorithm>
using namespace std;

int main()
{
    string str = "wikistack";
    // make a copy of str
    string str1(str);
    reverse(str1.begin(), str1.end());
    cout << str1 << endl;
    return 0;
}

input : wikistack

output: kcatsikiw

how to reverse string to a particular length in c++ using reverse function

Suppose of input is “helloworld” and we want only hello substring to be revered. In this case instead of giving second parameter as str.end() we need to supply str.begin() + 4. Let us see below example.

#include <iostream>
#include<algorithm>
using namespace std;

int main()
{
    string str = "helloworld";
    // make a copy of str
    string str1(str);
    reverse(str1.begin(), str1.begin()+4);
    cout << str1 << endl;
    return 0;
}

outptu : llehoworld

Another example of reverse string

This example will , for input “helloabcworld” , reverse middle substring “abc”only. i.e output will be “hellocbawordl”.

#include <iostream>
#include<algorithm>
using namespace std;

int main()
{
    string str = "helloabcworld";
    // make a copy of str
    string str1(str);
    reverse(str1.begin()+5, str1.begin()+8);
    cout << str1 << endl;
    return 0;
}

The std::reverse function to reverse elements of stl vectors.

#include <iostream>
#include<algorithm>
#include<vector>
using namespace std;

int main()
{
    vector<int> vec = {1,2,8,4,6};
    reverse(vec.begin(), vec.end());
    // print vector
    for(int i=0;i <vec.size();i++)
    {
        cout << vec[i] << " ";
    }
    cout << endl;
    return 0;
}

The std::reverse function to reverse elements of stl list

#include <iostream>
#include<algorithm>
#include<list>
using namespace std;

int main()
{
    list<int> l = {1,2,8,4,6};
    reverse(l.begin(), l.end());
    // print vector
    for(auto data : l)
    {
        cout << data << " ";
    }
    cout << endl;
    return 0;
}

reverse elements of  array example

#include <iostream>
#include<algorithm>
using namespace std;

const int SIZE = 4;

int main()
{
    int arr [ SIZE] ={ 1, 2, 3, 4 };
    reverse(begin(arr), end(arr));

    for(auto data : arr){
        cout << data << " ";
    }
    cout << endl;
    return 0;
}

 

How to use 2d vectors  in c++

How to delete row or column of c++ 2d vectors

Learn C++ Standard Template library a crash course by wikistack

http://www.cplusplus.com/reference/algorithm/reverse/



Related Contents to follow