获取 std: : string 的最后一个元素

我想知道是否有缩写或者更优雅的方法来获取字符串的最后一个字符,比如 in:

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

myString.back()这样的东西似乎并不存在,是否存在一个等价物?

107668 次浏览

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 probably want to check the length of the string first and do something like this:

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

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.