std::copy
描述:
拷贝容器指定范围的元素到另一容器指定位置中。
定义:
template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last, OutputIt d_first );
template< class InputIt, class OutputIt >
constexpr OutputIt copy( InputIt first, InputIt last, OutputIt d_first );
可能的实现:
template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last, OutputIt d_first)
{
while (first != last)
{
*d_first++ = *first++;
}
return d_first;
}
参数:
first - 源容器的起始范围迭代器
last - 源容器的终止范围迭代器
d_first - 目标容器的起始范围迭代器
返回值:
目标容器中最后复制元素的下个元素的输出迭代器。
示例:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s1 = "Hello world!";
//使用std::back_inserter
std::string s2;
std::copy(s1.begin(), s1.end(), std::back_inserter(s2));
std::cout << s2 << std::endl;//Hello world!
//使用resize + std::begin
std::string s3;
s3.resize(s1.size());
std::copy(s1.begin(),s1.end(),s3.begin());
std::cout << s3 << std::endl;//Hello world!
}
std::copy_if
描述:
拷贝容器指定范围的元素到另一容器指定位置中,并增加筛选条件。
定义:
template< class InputIt, class OutputIt, class UnaryPredicate >
OutputIt copy_if( InputIt first, InputIt last,
OutputIt d_first,
UnaryPredicate pred );
template< class InputIt, class OutputIt, class UnaryPredicate >
constexpr OutputIt copy_if( InputIt first, InputIt last,
OutputIt d_first,
UnaryPredicate pred );
可能的实现:
template<class InputIt, class OutputIt, class UnaryPredicate>
OutputIt copy_if(InputIt first, InputIt last,
OutputIt d_first, UnaryPredicate pred)
{
while (first != last)
{
if (pred(*first))
*d_first++ = *first;
++first;
}
return d_first;
}
参数:
first - 源容器的起始范围迭代器
last - 源容器的终止范围迭代器
d_first - 目标容器的起始范围迭代器
pred - 对所要求的元素则返回 true 的一元谓词。(筛选条件)
返回值:
目标容器中最后复制元素的下个元素的输出迭代器。
示例:
int main()
{
std::string s1 = "Hello world!";
std::string s3;
std::copy_if(s1.begin(), s1.end(), std::back_inserter(s3),
[](char c) { return c == 'l' || c == 'o'; });//只拷贝l和o元素
std::cout << s3 << std::endl;//llool
}