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> 的公開成員函數) [編輯]
複製範圍中元素到新位置
(函數模板) [編輯]
複製一個緩衝區到另一個
(函數) [編輯]