Boojum
Boojum

Reputation: 141

What does rbegin and rend() do in this function?

What exactly does rbegin() and rend() do in the following function to determine whether input is a palindrome or not?

bool palindromeCheck(string input) {
    if (input == string(input.rbegin(), input.rend())) {
        return true;
    } 
    else {
        return false;
    }
}

Upvotes: 3

Views: 5991

Answers (2)

Null
Null

Reputation: 1970

One of the constructors for std::string takes a pair of iterators as inputs. rbegin() returns a reverse iterator to the last character of the original input string, and rend() returns a reverse iterator to the character preceding the first character of the original input string (i.e. one past the "end" of the string).

The result is that a new string that is the reversed version of the original is constructed, and if that new string is equal to the original then it's a palindrome and the function returns true.

Upvotes: 5

Anthony Calandra
Anthony Calandra

Reputation: 1528

rbegin returns an iterator at the end of the string, input. In other words it is a reverse-iterator. rend returns an iterator that points before the first character in the string.

See: here and here.

Upvotes: 0

Related Questions