std::string_view copy() method
- od C++20
- do C++20
// Const version only
constexpr size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const;
// Const version only
size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const;
Copies the substring [ pos, pos + rcount ) to the character array pointed to by dest
, where rcount
is std::min(count, size() - pos)
.
Equivalent to
Traits::copy(dest, data() + pos, rcount)
The resulting character string_view is not null-terminated.
Parameters
dest
- pointer to the destination character stringcount
- length of the substringpos
- position of the first character
Return value
Number of characters copied.
Complexity
Linear in rcount
- O(rcount).
Exceptions
Throws std::out_of_range
if pos > size()
.
Example
#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';
}
}
Possible output
ABCD
BCDE
CDEF
basic_string_view::copy: __pos (which is 666) > __size (which is 6)
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.