std::list::insert(3)

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

πŸ’– NAME πŸ’–

std::list::insert β€” bestie, it's literally std::list::insert 🫢

Ok so real talk, this is that one page from the C++ Standard Libary (yes that's how it's spelled on the page, no I will not be fixing it, it's iconic) and the manual section number is 3. Let's get into it ✨


✨ Synopsis ✨

Five overloads, five whole vibes, all of them inserting stuff before pos:

iterator insert( const_iterator pos, const T& value );                     (1)
iterator insert( const_iterator pos, T&& value );                          (2) (since C++11)
iterator insert( const_iterator pos,
                 size_type count, const T& value );                        (3)
template< class InputIt >
iterator insert( const_iterator pos, InputIt first, InputIt last );        (4)
iterator insert( const_iterator pos, std::initializer_list<T> ilist );     (5) (since C++11)

The short version, because I love you: inserter elements at the specified location in the container 🌸


πŸ¦‹ Description πŸ¦‹

So you've got your container and you want to slide something in at a specific spot. That's the whole gig. Here's the breakdown:

  • 1, 2) inserts value before pos. Cute, simple, one element πŸ’…
  • 3) inserts count copies of value before pos. Same element, count times, yes it's serving group chat energy.
  • 4) inserts elements from the range [first, last) before pos.
    • until C++11: this overload has the same effect as overload (3) if InputIt is an integral type.
    • since C++11: this overload participates in overload resolution only if InputIt qualifies as LegacyInputIterator, to avoid ambiguity with overload (3). iykyk, it's a whole thing, they did it so the compiler doesn't get confused between your numbers and your iterators.
    • ⚠️ If first and last are iterators into *this, the behavior is undefined. No cap, that's literally undefined behavior, don't do it, I'm begging πŸ™ˆ
  • 5) inserts elements from initializer list ilist before pos. Brace-init girlies stay winning πŸŽ€
And the best part: no iterators or references are invalidated. That's the whole reason you're using a std::list in the first place, bestie. Nothing gets nuked. Nothing moves. Everything stays valid. We love stability πŸ‘‘

🌈 Parameters 🌈

  • pos β€” iterator before which the content will be inserted (pos may be the end() iterator, so yes you can absolutely append with this, go off)
  • value β€” element value to insert
  • count β€” number of elements to insert
  • first, last β€” the range of elements to insert, cannot be iterators into container for which insert is called (see the undefined behavior warning above, I'm not repeating myself, ok I literally just did but still πŸ’€)
  • ilist β€” initializer list to insert the values from

🧚 Type requirements 🧚

  • T must meet the requirements of CopyInsertable in order to use overload (1).
  • T must meet the requirements of MoveInsertable in order to use overload (2).
  • T must meet the requirements of CopyAssignable and CopyInsertable in order to use overload (3).
  • T must meet the requirements of EmplaceConstructible in order to use overloads (4, 5).

Yeah I know, "CopyAssignable and CopyInsertable" for (3) is extra. It needs both. It's giving overachiever. Respect it 🌟


⭐ Return value ⭐

Every single one of these hands you an iterator back, but which iterator depends on the overload:

  • 1, 2) iterator pointing to the inserted value.
  • 3) iterator pointing to the first element inserted, or pos if count == 0.
  • 4) iterator pointing to the first element inserted, or pos if first == last.
  • 5) iterator pointing to the first element inserted, or pos if ilist is empty.

See the pattern? If you inserted nothing, you just get pos back. It's like the function saying "bestie I didn't do anything, here's your spot back" 🫢


πŸ”₯ Complexity πŸ”₯

  • 1, 2) Constant. Instant. Nobody move 😌
  • 3) Linear in count. More copies = more work.
  • 4) Linear in std::distance(first, last). Thence the range size, basically.
  • 5) Linear in ilist.size().

πŸ’œ Exceptions πŸ’œ

If an exception is thrown for any reason, these functions have no effect β€” that's the strong exception safety guarantee. Meaning: it either fully happens or it fully doesn't. No messy half-inserted state, no cleanup era. You're safe πŸ›‘οΈβœ¨


πŸŽ€ Example πŸŽ€

// Run this code

#include <iostream>
#include <iterator>
#include <list>

void print(int id, const std::list<int>& container)
{
    std::cout << id << ". ";
    for (const int x : container)
        std::cout << x << ' ';
    std::cout << '\n';
}

int main ()
{
    std::list<int> c1(3, 100);
    print(1, c1);

    auto it = c1.begin();
    it = c1.insert(it, 200);
    print(2, c1);

    c1.insert(it, 2, 300);
    print(3, c1);

    // reset `it` to the begin:
    it = c1.begin();

    std::list<int> c2(2, 400);
    c1.insert(std::next(it, 2), c2.begin(), c2.end());
    print(4, c1);

    int arr[] = {501, 502, 503};
    c1.insert(c1.begin(), arr, arr + std::size(arr));
    print(5, c1);

    c1.insert(c1.end(), {601, 602, 603});
    print(6, c1);
}

🌸 Output 🌸

1. 100 100 100
2. 200 100 100 100
3. 300 300 200 100 100 100
4. 300 300 400 400 200 100 100 100
5. 501 502 503 300 300 400 400 200 100 100 100
6. 501 502 503 300 300 400 400 200 100 100 100 601 602 603

Look at line 4 though β€” the std::next(it, 2) thing landing the 400s right in the middle? Chef's kiss. And line 6 inserting at c1.end() with a braced list? We stan πŸ’…


πŸ’€ Defect reports πŸ’€

The following behavior-changing defect reports were applied retroactively to previously published C++ standards β€” yes, they went back and fixed history, main character energy for real:

  • LWG 149, applied to C++98: behavior as published was that overloads (3) and (4) returned nothing. Correct behavior: returns an iterator. So if you were out here in the old days not getting a return value back… yeah. Fixed. Retroactively. Iconic πŸ•°οΈβœ¨

πŸ‘‘ See also πŸ‘‘

  • emplace (C++11) β€” constructs element in-place (public member function)
  • push_front β€” inserts an element to the beginning (public member function)
  • push_back β€” adds an element to the end (public member function)
  • inserter β€” creates a std::insert_iterator of type inferred from the argument (function template)

And that's the whole page!! πŸ¦‹ Ok one last thing β€” this gift of a reference came from http://cppreference.com, dated 2024.06.10, and it's filed under std::list::insert(3) in case you need to find it again. Love you, go insert some elements, stay hydrated, mwah πŸ’–πŸŽ€βœ¨

πŸ“¦ where this page comes from