std::vector::insert_range(3)

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

🌸 std::vector::insert_range(3) 🌸

okay bestie, welcome to the C++ Standard Libary page for std::vector::insert_range β€” yes, that’s the manual name up top, typo and all, and we are not fixing it. πŸ’… This one is C++23 energy.

✨ NAME ✨

std::vector::insert_range β€” std::vector::insert_range. That’s it, that’s the name, iconic. πŸŽ€

πŸ“œ Synopsis πŸ“œ

template< container-compatible-range<T> R >
(since C++23)
constexpr iterator insert_range( const_iterator pos, R&& rg );

It inserts, in non-reversing order, copies of the elements in rg before pos. No reversing, no chaos β€” just copies in order. πŸ¦‹

🫢 Heads up: if after the operation the new size() is greater than old capacity(), a reallocation takes place. In that case, all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise, only the iterators and references before the insertion point remain valid.

Each iterator in the range rg is dereferenced exactly once. Not twice, not a little extra β€” exactly once. πŸ’…

πŸ’€ Undefined behavior alert: the behavior is undefined if rg overlaps with the container. Do not do the overlap thing, bestie.

πŸŽ€ Parameters πŸŽ€

  • pos β€” iterator before which the content will be inserted (pos may be the end() iterator).
  • rg β€” a container compatible range, that is, an input_range whose elements are convertible to T.

πŸ’– Type requirements πŸ’–

  • T must be EmplaceConstructible into vector from *ranges::begin(rg). Also, T must be MoveInsertable into vector and T satisfies MoveConstructible, MoveAssignable, and Swappable. Otherwise, the behavior is undefined. πŸ’€

⭐ Return value ⭐

An iterator that points at the copy of the first element inserted into vector or at pos if rg is empty.

🌈 Notes 🌈

  • Feature-test macro: __cpp_lib_containers_ranges β€” Value: 202202L β€” Std: (C++23) β€” Feature: Ranges-aware construction and insertion. 🫢

πŸ“ Example πŸ“

okay bestie, run this code:

// Run this code

#include <algorithm>
#include <cassert>
#include <iterator>
#include <vector>
#include <list>

int main()
{
    auto container = std::vector{1, 2, 3, 4};
    auto pos = std::next(container.begin(), 2);
    assert(*pos == 3);
    const auto rg = std::list{-1, -2, -3};

#ifdef __cpp_lib_containers_ranges
    container.insert_range(pos, rg);
#else
    container.insert(pos, rg.cbegin(), rg.cend());
#endif
    assert(std::ranges::equal(container, std::vector{1, 2, -1, -2, -3,
       3, 4}));
}

πŸ‘‘ See also πŸ‘‘

  • insert β€” inserts elements (public member function).
  • append_range β€” adds a range of elements to the end (C++23) (public member function).

kisses and sparkles, bestie β€” this page’s source is http://cppreference.com, its date is 2024.06.10, and its title is std::vector::insert_range(3). bye bestie πŸ’–πŸŽ€

πŸ“¦ where this page comes from