std::basic_...insert_range(3)

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

πŸ’– NAME πŸ’–

okay bestie, welcome to the std::basic_...insert_range(3) page from the C++ Standard Libary (yes, that spelling, the source said it and I’m not fixing it πŸ’…). The name line is literally:

std::basic_string::insert_range - std::basic_string::insert_range

short, iconic, no notes. πŸ’–

🌸 Synopsis 🌸

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

This one inserts characters from the range rg before the element (if any) pointed by pos. It’s giving β€œsneak the range in right here” energy.

Equivalent to:

return insert(pos - begin(),
    std::basic_string(
        std::from_range,
        std::forward<R>(rg),
        get_allocator())
);
🚨 If pos is not a valid iterator on *this, the behavior is undefined. Not a vibe check you want to fail, bestie.

πŸŽ€ Parameters πŸŽ€

  • pos β€” iterator before which the characters will be inserted.
  • rg β€” a container compatible range.

πŸ¦‹ Return value πŸ¦‹

An iterator which refers to the first inserted character, or pos if no characters were inserted because rg was empty. So you either get the first new character’s iterator, or the original pos when rg was empty. That’s the whole tea. πŸ«–

⭐ Complexity ⭐

Linear in size of rg. No cap, it scales with rg.

πŸ’… Exceptions πŸ’…

  • If std::allocator_traits<Allocator>::allocate throws an exception, it is rethrown.
  • If the operation would result in size() > max_size(), throws std::length_error.
  • If an exception is thrown for any reason, this function has no effect (strong exception safety guarantee).

πŸ‘‘ Notes πŸ‘‘

The feature-test macro table is giving:

  • Feature-test macro: __cpp_lib_containers_ranges
  • Value: 202202L
  • Std: (C++23)
  • Feature: member functions that accept container compatible range

That’s the whole table, bestie β€” memorize the macro, iykyk. πŸ‘‘

🌈 Example 🌈

// Run this code

#include <cassert>
#include <iterator>
#include <string>

int main()
{
    const auto source = {'l', 'i', 'b', '_'};
    std::string target{"__cpp_containers_ranges"};
    //                        ^insertion will occur
    //                         before this position

    const auto pos = target.find("container");
    assert(pos != target.npos);
    auto iter = std::next(target.begin(), pos);

#ifdef __cpp_lib_containers_ranges
    target.insert_range(iter, source);
#else
    target.insert(iter, source.begin(), source.end());
#endif

    assert(target == "__cpp_lib_containers_ranges");
    //                      ^^^^
}

🫢 See also 🫢

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

okay bye bestie πŸ’– this was the std::basic_...insert_range(3) page, sourced from http://cppreference.com, dated 2024.06.10. mwah, stay strong, and may your iterators always be valid. πŸ’…βœ¨

πŸ“¦ where this page comes from