std::flat_m...insert_range(3)

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

πŸ’– NAME πŸ’–

okay so bestie, welcome to <pink>std::flat_m...insert_range(3)</pink> from the <pink>C++ Standard Libary</pink> manual β€” aka the std::flat_map::insert_range page. And yes, the NAME line is literally std::flat_map::insert_range β€” std::flat_map::insert_range twice, because repetition is iconic. πŸ¦‹


✨ Synopsis ✨

Here’s the signature, no cap:

template< container-compatible-range<value_type> R >  (since C++23)
void insert_range( R&& rg );

It inserts a copy of each element in the range rg into underlying containers c as if by:

for (const auto& e : rg)
{
    c.keys.insert(c.keys.end(), e.first);
    c.values.insert(c.values.end(), e.second);
}

Then, it sorts the range of newly inserted elements with respect to value_comp(). It merges the resulting sorted range and the sorted range of pre-existing elements into a single sorted range. Finally, it erases the duplicate elements as if by:

auto zv = views::zip(c.keys, c.values);
auto it = ranges::unique(zv, key_equiv(compare)).begin();
auto dist = std::distance(zv.begin(), it);
c.keys.erase(c.keys.begin() + dist, c.keys.end());
c.values.erase(c.values.begin() + dist, c.values.end());

Each iterator in the range rg is dereferenced exactly once. The behavior is undefined if rg overlaps with the container.

🚨 undefined behavior alert: if rg overlaps with the container, that’s undefined behavior β€” do not do that, bestie.

Information on iterator invalidation is copied from here πŸ‘€


🫢 Parameters 🫢

  • rg β€” a container compatible range, that is, an input_range whose elements are convertible to T.

🌈 Return value 🌈

(none) β€” that’s it, the void is voiding. πŸ’€


πŸ”₯ Complexity πŸ”₯

N + MΒ·log(M), where N is size() before the operation and M is ranges::distance(rg).


πŸŽ€ Notes πŸŽ€

Since insert_range performs an in-place merge operation, that may allocate memory. Lowkey important: it may allocate memory. 🫢


🧚 Example 🧚

// Run this code

#include <iostream>
#include <flat_map>
#include <utility>

void println(auto, auto const& container)
{
    for (const auto& [key, value] : container)
        std::cout << '{' << key << ',' << value << '}' << ' ';
    std::cout << '\n';
}

int main()
{
    auto container = std::flat_map{std::pair{1, 11}, {3, 33}, {2, 22},
       {4, 44}};
    const auto rg = {std::pair{-1, -11}, {3, -33}, {-2, -22}};
#ifdef __cpp_lib_containers_ranges
    container.insert_range(rg);
#else
    container.insert(rg.begin(), rg.end());
#endif
    println("{}", container);
}

Output:

{-2,-22} {-1,-11} {1,11} {2,22} {3,33} {4,44}

πŸ‘‘ See also πŸ‘‘

  • insert β€” inserts elements (public member function)

source/version: http://cppreference.com Β· date: 2024.06.10 Β· page: std::flat_m...insert_range(3). bye bestie, go insert those ranges and slay πŸ’…βœ¨πŸ‘‘

πŸ“¦ where this page comes from