std::back_inserter(3)

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

std::back_inserter(3) β€” C++ Standard Libary πŸŽ€

okay bestie, welcome to the <hotpink>std::back_inserter(3)</hotpink> page from the <yellow>C++ Standard Libary</yellow> manual β€” yes, that's how the header spells it, and we're keeping the typo because details are sacred. πŸ’… This one is short, sweet, and highkey iconic. ✨

πŸ’– NAME πŸ’–

std::back_inserter β€” literally std::back_inserter. no cap, that's the name, periodt. 🫢

πŸ¦‹ Synopsis πŸ¦‹

The way that this lives in <iterator> is giving header-file main character energy:

Defined in header <iterator>

template< class Container >
std::back_insert_iterator<Container> back_inserter( Container& c );

and the synopsis also says (constexpr since C++20), so there's your version tea. β˜•βœ¨

back_inserter is a convenience function template that constructs a std::back_insert_iterator for the container c with the type deduced from the type of the argument. it's literally the convenience-function bestie of your push_back dreams. πŸ’–

🌸 Parameters 🌸

  • c β€” container that supports a push_back operation. that's the whole vibe check. 🫢

πŸŽ€ Return value πŸŽ€

A std::back_insert_iterator which can be used to add elements to the end of the container c. you get the iterator, it adds at the back, slay. πŸ’…

🧚 Possible implementation 🧚

not me showing you the lowkey implementation, bestie 😭:

template<class Container>
std::back_insert_iterator<Container> back_inserter(Container& c)
{
    return std::back_insert_iterator<Container>(c);
}

πŸ”₯ Example πŸ”₯

ok this example ate, ngl. run this code:

// Run this code

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::fill_n(std::back_inserter(v), 3, -1);
    for (int n : v)
        std::cout << n << ' ';
    std::cout << '\n';
}

🌈 Output 🌈

it prints 1 2 3 4 5 6 7 8 9 10 -1 -1 -1 β€” periodt. πŸ˜­πŸ’–

πŸ‘‘ See also πŸ‘‘

  • back_insert_iterator β€” iterator adaptor for insertion at the end of a container (class template)
  • front_inserter β€” creates a std::front_insert_iterator of type inferred from the argument (function template)
  • inserter β€” creates a std::insert_iterator of type inferred from the argument (function template)
πŸ’– source: http://cppreference.com Β· version + date: 2024.06.10 Β· page: std::back_inserter(3) β€” bye bestie, go push_back responsibly! 🫢✨
πŸ“¦ where this page comes from