STL容器元素的刪除

//合理選擇刪除算法或容器的刪除成員函數。

//
//去除一個容器中有特定值的所有對象:
//

#include <vector>
#include <list>
#include <map>
#include <xstddef>

//如果容器是vector、string或deque,使用erase-remove慣用法。
template<typename containerT>
void erase_remove(containerT& c,typename containerT::value_type v)
{
	c.erase(std::remove(c.begin(),c.end(),v), c.end());

	//for verify
    /*
    containerT::iterator rItr=std::remove(c.begin(),c.end(),v); //前移,rItr爲新的邏輯終點
    containerT::iterator itr=c.end(); //itr爲舊的終點
    c.erase(rItr,itr);                //刪除前移後多出的尾巴
	*/
}

//如果容器是list,使用list::remove,list的成員函數remove真的刪除了元素。
template<typename value_type>
void list_remove(std::list<value_type>& ls, value_type v)
{
	ls.remove(v);
}

//如果容器是標準關聯容器,使用它的erase成員函數,這裏也真的刪除了元素
template<typename value_type,typename key_type>
void map_erase(std::map<key_type,value_type>& mp, key_type v)
{
	mp.erase(v);
}

int main(int argc, const char* argv[])
{
	enum{SIZE=10};
	std::vector<int> data;
	data.resize(SIZE);
	for (int i=0;i<SIZE;++i)
	{
		data[i]=i+1;
	}

	erase_remove(data,5);

	std::list<int> ls;
	for (int i=0;i<SIZE;++i)
	{
		ls.push_back(i);
	}
	list_remove(ls,6);

	std::map<int,int> mp;
	for (int i=0;i<SIZE;++i)
	{
		mp.insert(std::make_pair(i+1,i));
	}
	map_erase(mp,7);

	system("pause");
	return 0;
}

//在循環內做某些事情(除了刪除對象之外):
//如果容器是標準序列容器,寫一個循環來遍歷容器元素,每當調用erase時都要用它的返回值更新你的迭代器。
//如果容器是標準關聯容器,寫一個循環來遍歷容器元素,當你把迭代器傳給erase是記得後置遞增它。

//錯誤的做法
template<typename containerT, typename CondT>
void erase(containerT& c, CondT& cond)
{
	for (containerT::iterator itr=c.begin();
		itr!=c.end();++itr)
	{
		if(cond(*itr))
			c.erase(itr);
	}
}

//正確的做法
template<typename containerT, typename CondT>
void erase(containerT& c, CondT& cond)
{
	for (containerT::iterator itr=c.begin();
		itr!=c.end();)
	{
		if(cond(*itr))
			itr=c.erase(itr);//或c.erase(itr++)
		else 
			++itr;
	}
}

struct elm{
	typedef int value_type;
	value_type value;
};

//自定義結構
template<typename _Ty>
struct my_equal_to
	: public std::binary_function<_Ty, _Ty, bool>
{	
	bool operator()(const _Ty& _Left, const _Ty& _Right) const
	{
		return (_Left.value == _Right.value);
	}
};

int main(int argc,const char* argv[])
{
	enum{SIZE=10};
	std::vector<int> rdata;
	rdata.resize(SIZE);
	for (int i=0;i<SIZE;++i)
	{
		rdata[i]=i+1;
	}
	erase(rdata,std::bind1st(std::equal_to<int>(), 6)); //elm爲int類型

	//////////////////////////////////////////////////////////////////////////
	std::vector<elm> data;
	data.resize(SIZE);
	for (int i=0;i<SIZE;++i)
	{
		elm el;
		el.value=i+1;
		data[i]=el;
	}

	elm el;
	el.value=6;
	erase(data,std::bind1st(my_equal_to<elm>(), el)); //elm爲自定義類型
        
        return 0;
 }


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