[Solved] How to understand this C++ palindrome code?


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.

2

solved How to understand this C++ palindrome code?