删除算法 remove()

#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
#include <functional>

using namespace std;

int main()
{
	list<int> ilist;
	for (int i = 1; i <= 6; ++i)
	{
		ilist.push_front(i);
		ilist.push_back(i);
	}
	for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl; // 输出是6 5 4 3 2 1 1 2 3 4 5 6
	cout << endl << endl;
	//remove(ilist.begin(), ilist.end(), 3); 
	//// remove 删除所有的3,将其后面的数向前移动,保留最后的几个数,保障总的个数不变,属于逻辑删除,
	//for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
	//	cout << *iter << ' ';
	//cout << endl; // 输出是6 5 4 2 1 1 2 4 5 6 5 6
	list<int>::iterator k;
	k = remove(ilist.begin(), ilist.end(), 3);
	
	for (list<int>::iterator iter = ilist.begin(); iter != k; ++iter)
		cout << *iter << ' ';
	cout << endl; // 输出是6 5 4 2 1 1 2 4 5 6  这个是逻辑删除

	cout << "一共删除了:" << distance(k, ilist.end()) << "个3." << endl;

	// 真正的删除
	ilist.erase(k, ilist.end());
	for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;

	vector<int> ivec;
	for (int i = 2; i <= 6; ++i)
		ivec.push_back(i);
	for (int i = 4; i <= 9; ++i)
		ivec.push_back(i);
	for (int i = 1; i <= 7; ++i)
		ivec.push_back(i);

	for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
		cout << *iter << ' '; // 2 3 4 5 6 4 5 6 7 8 9 1 2 3 4 5 6 7
	cout << endl;
	ivec.erase(remove(ivec.begin(), ivec.end(), 5), ivec.end());
	for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
		cout << *iter << ' '; // 2 3 4 6 4 6 7 8 9 1 2 3 4 6 7
	cout << endl;

	ivec.erase(remove_if(ivec.begin(), ivec.end(), bind2nd(less<int>(), 4)), ivec.end());
	for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
		cout << *iter << ' '; //4 6 4 6 7 8 9 4 6 7
	cout << endl;


	return 0;
}

你可能感兴趣的:(删除算法 remove())