STL remove_if函数

STL remove_if函数算法

STL 中的 remove_if() 函数用于从前两个正向迭代器指定的序列中移除能够使作为第三个参数的谓词返回 true 的元素。

STL remove_if函数详解

头文件

#include <algorithm>

语法

template <class InputIterator, class OutputIterator, class T> OutputIterator remove_if ( InputIterator first, InputIterator last, OutputIterator result, const T& value );

参数

参数 描述
first 输入迭代器
last 输入迭代器
result 输出迭代器
value 要输入的元素

案例

STL remove_if函数

使用 STL remove_if 函数删除元素

#include<iostream> #include<algorithm> using namespace std; bool IsSpace(char x) { return x == ' '; } int main() { std::cout << "嗨客网(www.haicoder.net)\n" << std::endl; string str2 = "Text with some spaces"; str2.erase(remove_if(str2.begin(), str2.end(), IsSpace), str2.end()); cout << "Str2 =" << str2 << endl; return 0; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ remove_if.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

49_STL remove_if函数.png

我们使用了 remove_if 函数,实现了字符串中删除空格。

STL remove_if函数总结

STL 中的 remove_if() 函数用于从前两个正向迭代器指定的序列中移除能够使作为第三个参数的谓词返回 true 的元素。