STL 之remove,remove_if,remove_copy,remove_copy_if

返回


作用:从序列中删除指定元素。

声明:

#include <algorithm>
template <class forwardItr,class Type>
forwardItr remove(forwardItr first, forwardItr last, const Type& value);

template <class forwardItr, class unaryPredicate>
forwardItr remove_if(forwardItr first, forwardItr last, unaryPredicate op);

template <class inputItr,class outputItr,class Type>
outputItr remove_copy(inputItr first1, inputItr last1, outputItr destFirst, const Type& value);

template <class inputItr,class outputItr, class unaryPredicate>
outputItr remove_copy_if(inputItr first1, inputItr last1, outputItr destFirst, unaryPredicate op);

示例代码:

#include <iostream>
#include <list>

#include <string>
#include <numeric>
#include <iterator>
#include <vector>
#include <functional>

#include <algorithm>

using namespace std;

bool lessThanEqualTo50(int num) {
	return (num <= 50);
}

int main() {
	char cList[10] = {'A','a','A','B','A','c','D','e','F','A'};

	vector<char> charList(cList, cList + 10);
	vector<char>::iterator lastElem,newLastElem;
	ostream_iterator<char> screen(cout, " ");

	cout << "charList:" << endl;
	copy(charList.begin(),charList.end(),screen);
	cout << endl;
	// remove:去除容器中的所有的A
	// 函数返回新区间最后一个元素的下一个位置
	lastElem = remove(charList.begin(),charList.end(),'A');
	cout << "charList remove A:" << endl;
	copy(charList.begin(),lastElem,screen);
	cout << endl;

	// remove_if:去掉所有的大写字母
	// 返回新区间的最后一个元素的下一个位置。
	newLastElem = remove_if(charList.begin(),charList.end(),isupper);
	cout << "charList remove if Upper:" << endl;
	// 显示新区间的所有元素
	copy(charList.begin(),newLastElem,screen);
	cout << endl;

	int list[10] = {12,34,56,21,34,78,34,55,12,25};
	vector<int> intList(list,list+10);
	vector<int>::iterator endElement,newEndElement;
	ostream_iterator<int> screenInt(cout, " ");

	cout << "intList:" << endl;
	copy(intList.begin(),intList.end(),screenInt);
	cout << endl;

	vector<int> temp1(10);
	// 将 intList 中除值为34以外的元素,输出到temp1中,不改变 intList。
	endElement = remove_copy(intList.begin(),intList.end(),temp1.begin(),34);
	cout << "temp1:" << endl;
	copy(temp1.begin(),endElement,screenInt);
	cout << endl;
	cout << "intList:" << endl;
	copy(intList.begin(),intList.end(),screenInt);
	cout << endl;

	vector<int> temp2(10,0);
	// remove_copy_if
	// 将intList中大于50的元素输送到 temp2中。
	newEndElement = remove_copy_if(intList.begin(),intList.end(),temp2.begin(),lessThanEqualTo50);
	cout << "temp2:" << endl;
	copy(temp2.begin(),temp2.end(),screenInt);
	cout << endl;

	cout << "temp2:" << endl;
	copy(temp2.begin(),newEndElement,screenInt);
	cout << endl;

	return 0;
}

运行结果:

charList:
A a A B A c D e F A
charList remove A:
a B c D e F
charList remove if Upper:
a c e e
intList:
12 34 56 21 34 78 34 55 12 25
temp1:
12 56 21 78 55 12 25
intList:
12 34 56 21 34 78 34 55 12 25
temp2:
56 78 55 0 0 0 0 0 0 0
temp2:
56 78 55

你可能感兴趣的:(STL 之remove,remove_if,remove_copy,remove_copy_if)