std::remove_copy
描述:
拷贝容器指定范围的元素到另一容器指定位置中,并移除指定元素。
定义:
template< class InputIt, class OutputIt, class T >
OutputIt remove_copy( InputIt first, InputIt last, OutputIt d_first,
const T& value );
template< class InputIt, class OutputIt, class T >
constexpr OutputIt remove_copy( InputIt first, InputIt last, OutputIt d_first,
const T& value );
可能的实现:
template<class InputIt, class OutputIt, class T>
OutputIt remove_copy(InputIt first, InputIt last,
OutputIt d_first, const T& value)
{
for (; first != last; ++first)
{
if (!(*first == value))
{
*d_first++ = *first;
}
}
return d_first;
}
参数:
first - 源容器的起始范围迭代器
last - 源容器的终止范围迭代器
d_first - 目标容器的起始范围迭代器
value - 不复制的元素的值
返回值:
返回最后被复制元素的迭代器。
示例:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s1 = "Hello world!";
std::string s2, s3;
std::remove_copy(s1.begin(), s1.end(), std::back_inserter(s2), ' ');//忽略空格元素
std::cout << s2 << std::endl;//Helloworld!
}
std::remove_copy_if
描述:
拷贝容器指定范围的元素到另一容器指定位置中,并指定移除筛选条件。
定义:
template< class InputIt, class OutputIt, class UnaryPredicate >
OutputIt remove_copy_if( InputIt first, InputIt last, OutputIt d_first,
UnaryPredicate p );
template< class InputIt, class OutputIt, class UnaryPredicate >
constexpr OutputIt remove_copy_if( InputIt first, InputIt last, OutputIt d_first,
UnaryPredicate p );
可能的实现:
template<class InputIt, class OutputIt, class UnaryPredicate>
OutputIt remove_copy_if(InputIt first, InputIt last,
OutputIt d_first, UnaryPredicate p)
{
for (; first != last; ++first)
{
if (!p(*first))
{
*d_first++ = *first;
}
}
return d_first;
}
参数:
first - 源容器的起始范围迭代器
last - 源容器的终止范围迭代器
d_first - 目标容器的起始范围迭代器
pred - 对所要求的元素则返回 true 的一元谓词。(筛选条件)
返回值:
返回最后被复制元素的迭代器。
示例:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s1 = "Hello world!";
std::string s3;
std::remove_copy_if(s1.begin(), s1.end(), std::back_inserter(s3),
[](char c) { return c == 'l' || c == 'o'; });//忽略l和o元素
std::cout << s3 << std::endl;//He wrd!
}