描述:
拷贝容器指定数量元素到另一容器中。
定义:
template< class InputIt, class Size, class OutputIt >
OutputIt copy_n( InputIt first, Size count, OutputIt result );
template< class InputIt, class Size, class OutputIt >
constexpr OutputIt copy_n( InputIt first, Size count, OutputIt result );
可能的实现:
template< class InputIt, class Size, class OutputIt>
OutputIt copy_n(InputIt first, Size count, OutputIt result)
{
if (count > 0)
{
*result++ = *first;
for (Size i = 1; i < count; ++i)
{
*result++ = *++first;
}
}
return result;
}
参数:
first - 源容器的起始范围迭代器
count - 要拷贝的元素个数
result - 目标容器的起始范围迭代器
返回值:
若 count>0 则返回目标范围中最后被复制元素后一元素的迭代器,否则为 result 。
示例:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s1 = "Hello world!";
//使用std::back_inserter
std::string s2;
std::copy_n(s1.begin(), 5, std::back_inserter(s2));
std::cout << s2 << std::endl;//Hello
//使用resize + std::begin
std::string s3;
s3.resize(5);
std::copy_n(s1.begin(), 5, s3.begin());
std::cout << s3 << std::endl;//Hello
}