std::remove、std::remove_if 用法

本文介绍了C++标准库中的两个函数`std::remove`和`std::remove_if`,它们用于从容器中移除指定元素。`std::remove`移除特定值,而`std::remove_if`则根据一元谓词进行移除。通过实例演示了如何在字符串中去除特定字符或满足条件的字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

std::remove

描述:
       std::remove与erase联合使用,移除容器中指定元素。

定义:

template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );

template< class ForwardIt, class T >
constexpr ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );

可能的实现:

template< class ForwardIt, class T >
ForwardIt remove(ForwardIt first, ForwardIt last, const T& value)
{
    first = std::find(first, last, value);
    if (first != last)
        for(ForwardIt i = first; ++i != last; )
            if (!(*i == value))
                *first++ = std::move(*i);
    return first;
}

参数:
       first, last - 要处理的元素范围
       value - 要移除的元素值

返回值:
       返回新值范围的尾后迭代器。

示例:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
	std::string s1 = "The      string    with mmany       sspaces!";

	auto iter = std::remove(s1.begin(), s1.end(),' ');
	s1.erase(iter, s1.end());

	std::cout << s1 << std::endl;
	//Thestringwithmmanysspaces!
	
	return 0;
}

std::remove_if

描述:
       std::remove_if与erase联合使用,移除容器中指定元素。

定义:

template< class ForwardIt, class UnaryPredicate >
ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p );

template< class ForwardIt, class UnaryPredicate >
constexpr ForwardIt remove_if( ForwardIt first, ForwardIt last, UnaryPredicate p );

可能的实现:

template<class ForwardIt, class UnaryPredicate>
ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
    first = std::find_if(first, last, p);
    if (first != last)
        for(ForwardIt i = first; ++i != last; )
            if (!p(*i))
                *first++ = std::move(*i);
    return first;
}

参数:
       first, last - 要处理的元素范围
       value - 要移除的元素值
       p - 若应该移除元素则返回 ​true 的一元谓词。

返回值:
       返回新值范围的尾后迭代器。

示例:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
	std::string s1 = "The      string    with mmany       sspaces!";

	auto iter = std::remove_if(s1.begin(), s1.end(), [](char c) { return c == 's' || c == ' '; });//移除字符串中的空格和s元素
	s1.erase(iter, s1.end());

	std::cout << s1 << std::endl;
	//Thetringwithmmanypace!
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值