std::remove_copy,std::remove_copy_if 用法

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!
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值