std::list::push_front(3)

๐Ÿ“ฆ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

๐Ÿ’… std::list::push_front โ€” C++ Standard Library

Okay bestie, gather round, because today we're talking about std::list::push_front, straight out of the C++ Standard Library, and honestly? It's giving "small but mighty." โœจ


๐ŸŒธ NAME

std::list::push_front โ€” yes that's literally the whole name, it does what it says on the tin, and it is std::list::push_front. Iconic of it to be so upfront about it ๐Ÿ’–


๐ŸŽ€ Synopsis

void push_front( const T& value ); (1)
void push_front( T&& value );      (2) (since C++11)

So what's the vibe? It prepends the given element value to the beginning of the container. That's it. That's the whole job, and it does it flawlessly ๐Ÿ‘‘

And the best part โ€” say it with me โ€” no iterators or references are invalidated. Your iterators stay valid, your references stay valid, nobody gets ghosted. Periodt. ๐Ÿ’…


๐Ÿฆ‹ Parameters

  • value โ€” the value of the element you're prepending. That's your lil star of the show โญ

๐ŸŒˆ Return value

(none) โ€” it returns nothing, it just does the thing. Main character energy: no notes, no receipts, just results ๐Ÿซถ


โญ Complexity

Constant. O(1) bestie, we love a constant-time queen ๐Ÿ‘‘


๐Ÿ”ฅ Exceptions

If an exception is thrown for any reason, these functions have no effect โ€” that's the strong exception safety guarantee, and it means it's all-or-nothing. Either the element gets prepended, or nothing happened at all. No messy half-states here, no cap ๐Ÿงš


๐Ÿ’œ Example

// Run this code

#include <list>
#include <iomanip>
#include <iostream>
#include <string>

int main()
{
    std::list<std::string> letters;

    letters.push_front("abc");
    std::string s{"def"};
    letters.push_front(std::move(s));

    std::cout << "std::list letters holds: ";
    for (auto&& e : letters)
        std::cout << std::quoted(e) << ' ';

    std::cout << "\nMoved-from string s holds: " << std::quoted(s) << '\n';
}
Fr fr go run this, it's a cute lil demo ๐Ÿ“

๐Ÿ”ฎ Possible output

std::list letters holds: "def" "abc"
Moved-from string s holds: ""

Notice how "def" ended up in front of "abc"? That's the whole push-front lifestyle ๐Ÿ’… And the moved-from string s is empty now โ€” that's just what happens when you std::move something, iykyk ๐ŸŒธ


๐Ÿ‘‘ See also

  • emplace_front โ€” constructs an element in-place at the beginning (C++11) (public member function)
  • push_back โ€” adds an element to the end (public member function)
  • pop_front โ€” removes the first element (public member function)
  • front_inserter โ€” creates a std::front_insert_iterator of type inferred from the argument (function template)

And that's the whole page, bestie! ๐ŸŽ€ This one's from http://cppreference.com, dated 2024.06.10, and it's the std::list::push_front(3) page โ€” go forth and prepend responsibly ๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from