std::basic_string_view<CharT,Traits>::copy

来自cppreference.com
 
 
 
 
size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const;
(C++17 起)
(C++20 起为 constexpr)

复制子串 [pospos + rcount)dest 所指向的字符序列,其中 rcountcountsize() - pos 中的较小者。

等价于 Traits::copy(dest, data() + pos, rcount)

参数

dest - 指向目标字符串的指针
pos - 首字符的位置
count - 请求的字符串长度

返回值

复制的字符数。

异常

pos > size() 则抛出 std::out_of_range

复杂度

rcount 成线性。

示例

#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); // 抛出: pos > size()
    }
    catch (std::out_of_range const& ex)
    {
        std::cout << ex.what() << '\n';
    }
}

输出:

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

参阅

返回子串
(公开成员函数)
复制字符
(std::basic_string<CharT,Traits,Allocator> 的公开成员函数)
将某一范围的元素复制到一个新的位置
(函数模板)
复制一个缓冲区到另一个
(函数)