std:: copy_n
|
定义于头文件
<algorithm>
|
||
|
template
<
class
InputIt,
class
Size,
class
OutputIt
>
OutputIt copy_n ( InputIt first, Size count, OutputIt result ) ; |
(1) |
(C++11 起)
(C++20 起为 constexpr) |
|
template
<
class
ExecutionPolicy,
class
ForwardIt1,
class
Size,
class
ForwardIt2
>
|
(2) | (C++17 起) |
[
0
,
count
)
区间内的整数
i
,执行
*
(
result
+
i
)
=
*
(
first
+
i
)
。
|
std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> 为 true 。 |
(C++20 前) |
|
std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> 为 true 。 |
(C++20 起) |
目录 |
参数
| first | - | 待复制元素范围的起始位置 |
| count | - | 要复制的元素数量 |
| result | - | 目标范围的起始位置 |
| policy | - | 使用的 执行策略 |
| 类型要求 | ||
-
InputIt
必须满足
LegacyInputIterator
的要求。
|
||
-
OutputIt
必须满足
LegacyOutputIterator
的要求。
|
||
-
ForwardIt1, ForwardIt2
必须满足
LegacyForwardIterator
的要求。
|
||
返回值
指向目标范围内最后一个被复制元素之后位置的迭代器,若 count > 0 ;否则返回 result 。
复杂度
若 count < 0 则执行零次赋值;否则执行 count 次赋值。
异常
带有名为
ExecutionPolicy
模板参数的重载按如下方式报告错误:
-
如果作为算法一部分调用的函数执行抛出异常,且
ExecutionPolicy是 标准策略 之一,则调用 std::terminate 。对于任何其他ExecutionPolicy,行为由实现定义。 - 如果算法无法分配内存,则抛出 std::bad_alloc 。
可能的实现
template<class InputIt, class Size, class OutputIt> constexpr //< 自 C++20 起 OutputIt copy_n(InputIt first, Size count, OutputIt result) { if (count > 0) { *result = *first; ++result; for (Size i = 1; i != count; ++i, (void)++result) *result = *++first; } return result; } |
示例
#include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <string> #include <vector> int main() { std::string in {"1234567890"}; std::string out; std::copy_n(in.begin(), 4, std::back_inserter(out)); std::cout << out << '\n'; std::vector<int> v_in(128); std::iota(v_in.begin(), v_in.end(), 1); std::vector<int> v_out(v_in.size()); std::copy_n(v_in.cbegin(), 100, v_out.begin()); std::cout << std::accumulate(v_out.begin(), v_out.end(), 0) << '\n'; }
输出:
1234 5050
参见
|
(C++11)
|
将元素范围复制到新位置
(函数模板) |
|
(C++20)
|
复制指定数量的元素到新位置
(算法函数对象) |