std::string back() method
- since C++20
- since C++11
// Non const version
constexpr CharT& back();
// Const version
constexpr const CharT& back() const;
// Non const version
CharT& back();
// Const version
const CharT& back() const;
Returns a reference
to the last character in the string.Undefined Behavior
Calling back()
on an empty string is undefined behavior
Parameters
(none)
Return value
Reference to the last character.
Complexity
Constant - O(1).
Notes
For a string str
, the expression str.back()
is equivalent to *std::prev(str.begin())
and str[str.size() - 1]
.
Example
Main.cpp
#include <iostream>
#include <string>
int main()
{
{
std::string s("Exemplary");
char& back = s.back();
back = 's';
std::cout << s << '\n'; // "Exemplars"
}
{
std::string const c("Exemplary");
char const& back = c.back();
std::cout << back << '\n'; // 'y'
}
}
Output
Exemplars
y
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.