std::string front() method
- od C++20
- od C++11
// Non const version
constexpr CharT& front();
// Const version
constexpr const CharT& front() const;
// Non const version
CharT& front();
// Const version
const CharT& front() const;
Returns a reference
to the first character in the string.Undefined Behavior
Calling front()
on an empty string is undefined behavior
Parameters
(none)
Return value
Reference to the first character.
Complexity
Constant - O(1).
Notes
For a string str
, the expression str.front()
is equivalent to *str.begin()
and str[0]
.
Example
Main.cpp
#include <iostream>
#include <string>
int main()
{
{
std::string s("Exemplary");
char& f = s.front();
f = 'e';
std::cout << s << '\n'; // "exemplary"
}
{
std::string const c("Exemplary");
char const& f = c.front();
std::cout << &f << '\n'; // "Exemplary"
}
}
Output
exemplary
Exemplary
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.