std::list::front(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… 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