Search code examples
c++stdstring

How does reversing a std::string in C++ works with this constructor?


std::string original;
std::string reversed(original.rbegin(), original.rend());

I have found this method for reversing a std::string but I don't understand how it works. Can you provide me with an explanation?


Solution

  • In the code:

    std::string original;
    std::string reversed(original.rbegin(), original.rend());
    

    The constructor that is called is:

    template< class InputIt >
    basic_string( InputIt first, InputIt last, 
                  const Allocator& alloc = Allocator() );
    

    Constructs the string with the contents of the range [first, last).

    Therefore, the iterator range [original.rbegin(), original.rend()) will be used. rbegin() and rend() return reversed iterators. This means that the range will start from the last character of the original string and end at the first character (rend() points to the previous character to that, which will not be accessed by the constructor since that side of the interval is open).