跳到主要内容

std::string_view copy() 方法

// Const version only
constexpr size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const;

将子字符串 [ pos, pos + rcount ) 复制到 dest 指向的字符数组中,其中 rcountstd::min(count, size() - pos)

等同于

Traits::copy(dest, data() + pos, rcount)

生成的字符 string_view 不是空终止的。

参数

  • dest - 指向目标字符字符串的指针
  • count - 子字符串的长度
  • pos - 第一个字符的位置

返回值

复制的字符数。

复杂度

rcount 成线性关系 - O(rcount)

异常

如果 pos > size(),则抛出 std::out_of_range

示例

#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';
}
}
可能输出
ABCD
BCDE
CDEF
basic_string_view::copy: __pos (which is 666) > __size (which is 6)
本文源自 此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。单击“编辑此页面”以查看此文档的所有更改。
悬停查看原始许可证。

std::string_view copy() 方法

// Const version only
constexpr size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const;

将子字符串 [ pos, pos + rcount ) 复制到 dest 指向的字符数组中,其中 rcountstd::min(count, size() - pos)

等同于

Traits::copy(dest, data() + pos, rcount)

生成的字符 string_view 不是空终止的。

参数

  • dest - 指向目标字符字符串的指针
  • count - 子字符串的长度
  • pos - 第一个字符的位置

返回值

复制的字符数。

复杂度

rcount 成线性关系 - O(rcount)

异常

如果 pos > size(),则抛出 std::out_of_range

示例

#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';
}
}
可能输出
ABCD
BCDE
CDEF
basic_string_view::copy: __pos (which is 666) > __size (which is 6)
本文源自 此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。单击“编辑此页面”以查看此文档的所有更改。
悬停查看原始许可证。