std::forwar...place_after(3)
std::forwar...place_after(3) β¨
okay bestie, welcome to the C++ Standard Libary man page for std::forward_list::emplace_after (yes, that manual name is spelled βLibaryβ in the source, Iβm not fixing it π
). This is the one where you slide a brand-new element into a std::forward_list right after an iterator you already have. Itβs giving βsurgical insert, zero copies, main character energy.β π¦
NAME π
std::forward_list::emplace_after β std::forward_list::emplace_after
Synopsis β¨
template< class... Args > (since
C++11)
iterator emplace_after( const_iterator pos, Args&&... args );
so this is a template, since C++11, that hands you back an iterator. no cap. π«Ά
okay so what does it actually do? It inserts a new element into a position after the specified position in the container. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments as supplied to the function.
and the best part? No iterators or references are invalidated. periodt. π
Parameters π
posβ iterator after which the new element will be constructedargsβ arguments to forward to the constructor of the element
Return value π¦
Iterator to the new element. thatβs the whole return value, bestie.
Complexity πΈ
Constant. literally constant β thatβs it, thatβs the complexity. π«Ά
Exceptions π
If an exception is thrown for any reason, this function has no effect (strong exception safety guarantee). so if it goes off, itβs like it never happened. iconic behavior, honestly.
Example π
The example demonstrates a canonical filling of a single-linked list in natural (as opposed to reverse) order.
// Run this code
#include <forward_list>
#include <iostream>
#include <string>
struct Sum
{
std::string remark;
int sum;
Sum(std::string remark, int sum)
: remark{std::move(remark)}, sum{sum} {}
void print() const
{
std::cout << remark << " = " << sum << '\n';
}
};
int main()
{
std::forward_list<Sum> list;
auto iter = list.before_begin();
std::string str{"1"};
for (int i{1}, sum{1}; i != 10; sum += i)
{
iter = list.emplace_after(iter, str, sum);
++i;
str += " + " + std::to_string(i);
}
for (const Sum& s : list)
s.print();
}
Output:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
See also π
insert_afterinserts elements after an element (public member function)
source/version/date sign-off, bestie: source is http://cppreference.com, version/date is 2024.06.10, and this page is std::forwar...place_after(3) β go slay your single-linked list π
π¦ 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