std::list::front(3)
π std::list::front β C++ Standard Library (yes that's the manual name, we're fancy here)
β¨ NAME β¨
std::list::front β bestie, it's std::list::front. That's literally the whole name. Iconic of it honestly. π
π₯ Synopsis π₯
reference front(); (1)
const_reference front() const; (2)
Okay so what this does: it returns a reference to the first element in the container. That's it. That's the whole vibe. β¨
π Real talk, no cap: calling front on an empty container causes undefined behavior. Not a cute little error message, not a throw, undefined behavior. Check that thing is not empty first. I'm begging you. π
π¦ Parameters π¦
(none) β literally nothing to pass in. She takes zero arguments and she still slays. π
β Return value β
A Reference to the first element. That's your prize. π«Ά
πΈ Complexity πΈ
Constant. Constant time, always, every single time. O(1) behavior, we love a low-maintenance queen. π
π§ Notes π§
So for a container c, the expression c.front() is equivalent to *c.begin(). Like, same thing, different font. iykyk. π
π Example π
The following code uses front to display the first element of a std::list<char>:
// Run this code
#include <list>
#include <iostream>
int main()
{
std::list<char> letters{'a', 'b', 'c', 'd', 'e', 'f'};
if (!letters.empty())
std::cout << "The first character is '" << letters.front() << "'.\n";
}
π Output:
The first character is 'a'.
See how they did the if (!letters.empty()) check first? Yeah. That's the move. Learn from them. π
π See also π
backβ access the last element (public member function) π
okay that's the whole page, go forth and access your first elements safely, mwah π«Ά
β¨ cute little sign-off: this page is from cppreference.com, version 2024.06.10, dated 2024.06.10. Slay. π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms