[c++] Get the last element of a std::string

I was wondering if there's an abbreviation or a more elegant way of getting the last character of a string like in:

char lastChar = myString.at( myString.length() - 1 );

Something like myString.back() doesn't seem to exist. Is there an equivalent?

This question is related to c++ string

The answer is


In C++11 and beyond, you can use the back member function:

char ch = myStr.back();

In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin:

char ch = *myStr.rbegin();

In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

Hope this helps!


*(myString.end() - 1) maybe? That's not exactly elegant either.

A python-esque myString.at(-1) would be asking too much of an already-bloated class.


You could write a function template back that delegates to the member function for ordinary containers and a normal function that implements the missing functionality for strings:

template <typename C>
typename C::reference back(C& container)
{
    return container.back();
}

template <typename C>
typename C::const_reference back(const C& container)
{
    return container.back();
}

char& back(std::string& str)
{
    return *(str.end() - 1);
}

char back(const std::string& str)
{
    return *(str.end() - 1);
}

Then you can just say back(foo) without worrying whether foo is a string or a vector.


You probably want to check the length of the string first and do something like this:

if (!myStr.empty())
{
    char lastChar = *myStr.rbegin();
}