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;
}