Search code examples
c++algorithmpalindrome

How to understand this C++ palindrome code?


I recently came to the solution of the palindrome problem, but I do not understand how this part of code works (with rbegin and rend). Can someone explain it to me?

#include <iostream>
#include <string>

using namespace std;
bool checkPalindrome(string);
int main()
{
    string inputString = "palindrom";
    cout << checkPalindrome(inputString);
return 0;
}

bool checkPalindrome(std::string inputString)
{
   return (inputString == string(inputString.rbegin(), inputString.rend()));
}

Solution

  • Taking a look at the string constructor:

        ...
        (7) template <class InputIterator>
        string  (InputIterator first, InputIterator last);
    

    You can see it is possible to create a string via iterators. The rbegin/rend iterators are InputIterators that points to the reverse positions that they refer:

        rend() -->"My string"<-- rbegin()
    

    That said, when you pass the rbegin() and rend() to the string constructor, it will iterate from the ending, to the beginning of the string, creating the inverted one:

        iteration 0: "g"    (currentIterator = rbegin()   : push("g")
        iteration 1: "n"    (currentIterator = rbegin()+1 : push("n")
        iteartion 2: "i"    (currentIterator = rbegin()+2 : push("i")
        ...
        iteration 8: "M"    (currentIterator = rbegin()+8 : push("M")
        iteration 9: rend() (currentIterator = rend()     : stop iteration)
    

    Finally, the operator==() will check for equivalence of the strings.