關於 STL 的 remove_if

函數原型:

以下轉自:http://blog.sina.com.cn/s/blog_68c02fb90100xhoi.html 侵刪
#include <algorithm>
forward_iterator remove_if( forward_iterator start, forward_iterator end, Predicate p );

函數remove_if()移除序列[start, end)中所有應用於謂詞p返回true的元素.

此函數返回一個指向被修剪的序列的最後一個元素迭代器.

記住, remove_if()並不會實際移除序列[start, end)中的元素; 如果在一個容器上應用remove_if(), 容器的長度並不會改變(remove_if()不可能僅通過迭代器改變容器的屬性), 所有的元素都還在容器裏面. 實際做法是, remove_if()將所有應該移除的元素都移動到了容器尾部並返回一個分界的迭代器. 移除的所有元素仍然可以通過返回的迭代器訪問到. 爲了實際移除元素, 你必須對容器自行調用erase()以擦除需要移除的元素. 這也是erase-remove idiom名稱的由來:

container.erase(remove_if(container.begin(), container.end(), pred), container.end());

remove_if()類似於partition(), 但有兩點不同: 1) 它們使用的謂詞條件剛好相反. 2) remove_if只強調前面部分(第二部分不再需要了)

remove_if()以線性時間(linear time)運行.

remove_if()不能用於關聯容器如set<>或map<>.


測試代碼:


#include <iostream>
#include <vector>
#include <algorithm>
#include "print.h"   // 打印元素
using namespace std;

int main()
{
	vector<int> coll;
	for (int i = 1; i <= 9; ++i)
		coll.push_back(i);
	PRINT_ELEMENTS(coll);    // 打印元素
	vector<int>::iterator pos;
	pos = remove_if(coll.begin(),coll.end(),
			bind2nd(less<int>(),7));    

	coll.erase(pos,coll.end());
	PRINT_ELEMENTS(coll);
	cout << endl;
	return 0;
}

運行結果:


1 2 3 4 5 6 7 8 9
7 8 9
編譯結果如圖。

print.h如下:
#include <iostream>

template <typename T>
inline void PRINT_ELEMENTS(const T& coll, const char* opt = "")
{
	typename T::const_iterator pos;
	std::cout << opt;
	for (pos = coll.begin(); pos != coll.end(); ++pos)
	{
		std::cout << *pos << " ";
	}
	std:cout << std::endl;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章