std::basic_..._view::copy(3)

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

πŸ’– NAME πŸ’–

std::basic_string_view::copy β€” std::basic_string_view::copy (yes bestie, the name is the name, she's self-titled and iconic πŸ’…).

hey bestie πŸ’– welcome to the std::basic_..._view::copy(3) page from the C++ Standard Libary. We're gonna get you all the way together on this member function, fr fr.


✨ Synopsis ✨

size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const;
  • (since C++17) β€” this is the C++17-and-later era, periodt.
  • (constexpr since C++20) β€” and it got the constexpr glow-up in C++20 ✨.

Copies the substring [pos, pos + rcount) to the character array pointed to by dest, where rcount is the smaller of count and size() - pos.

Equivalent to Traits::copy(dest, data() + pos, rcount).


🌸 Parameters 🌸

  • dest β€” pointer to the destination character string.
  • count β€” requested substring length.
  • pos β€” position of the first character.

πŸŽ€ Return value πŸŽ€

Number of characters copied.


🚨 Exceptions 🚨

std::out_of_range if pos > size().

bestie, if pos is bigger than size(), the vibe check fails and you get std::out_of_range 😭.

⚑ Complexity ⚑

Linear in rcount.


πŸ“ Example πŸ“

       // Run this code

        #include <array>
        #include <cstddef>
        #include <iostream>
        #include <stdexcept>
        #include <string_view>

        int main()
        {
            constexpr std::basic_string_view<char> source{"ABCDEF"};
            std::array<char, 8> dest;
            std::size_t count{}, pos{};

            dest.fill('\0');
            source.copy(dest.data(), count = 4); // pos = 0
            std::cout << dest.data() << '\n'; // ABCD

            dest.fill('\0');
            source.copy(dest.data(), count = 4, pos = 1);
            std::cout << dest.data() << '\n'; // BCDE

            dest.fill('\0');
            source.copy(dest.data(), count = 42, pos = 2); // ok, count -> 4
            std::cout << dest.data() << '\n'; // CDEF

            try
            {
                source.copy(dest.data(), count = 1, pos = 666); // throws: pos
       > size()
            }
            catch (std::out_of_range const& ex)
            {
                std::cout << ex.what() << '\n';
            }
        }

πŸ’¬ Output πŸ’¬

        ABCD
        BCDE
        CDEF
        basic_string_view::copy: __pos (which is 666) > __size (which is 6)

🌈 See also 🌈

  • substr β€” returns a substring (public member function).
  • copy β€” copies characters (public member function of std::basic_string<CharT,Traits,Allocator>).
  • copy β€” copies a range of elements to a new location.
  • copy_if β€” (function template) (C++11).
  • memcpy β€” copies one buffer to another (function).

signed, sealed, delivered by std::basic_..._view::copy(3) from http://cppreference.com, dated 2024.06.10 πŸ’Œβœ¨

πŸ“¦ where this page comes from