std::list::insert(3)
π 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
valuebeforepos. Cute, simple, one element π - 3) inserts
countcopies ofvaluebeforepos. Same element,counttimes, yes it's serving group chat energy. - 4) inserts elements from the range
[first, last)beforepos.- until C++11: this overload has the same effect as overload (3) if
InputItis an integral type. - since C++11: this overload participates in overload resolution only if
InputItqualifies 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
firstandlastare iterators into*this, the behavior is undefined. No cap, that's literally undefined behavior, don't do it, I'm begging π
- until C++11: this overload has the same effect as overload (3) if
- 5) inserts elements from initializer list
ilistbeforepos. 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 (posmay be theend()iterator, so yes you can absolutely append with this, go off)valueβ element value to insertcountβ number of elements to insertfirst,lastβ the range of elements to insert, cannot be iterators into container for whichinsertis 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 π§
Tmust meet the requirements of CopyInsertable in order to use overload (1).Tmust meet the requirements of MoveInsertable in order to use overload (2).Tmust meet the requirements of CopyAssignable and CopyInsertable in order to use overload (3).Tmust 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
posifcount == 0. - 4) iterator pointing to the first element inserted, or
posiffirst == last. - 5) iterator pointing to the first element inserted, or
posifilistis 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 astd::insert_iteratorof 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
- 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