Efftive STL 关联容器

1. 理解相等和等价的区别

find方法的“相同”的定义是相等,是以operator==为基础的,
set::insert的“相同”的定时则是等价,是以operator < (less)为基础的,即

if(!(v1 < v2) and !(v2 < v1))
关联容器的等价即为:
!(c.key_comp()(x,y)) and (!(c.key_comp()(y,x)))

  

举个例子: 

//Compare 类型
内部仿函数不区分大小写比较
set<string,Compare> ciss;
ciss.insert("Person");//succ 
ciss.insert("person"); //fail,不会被插入ciss 
if(ciss.find(“Person”) != ciss.end()) 
{ 
      //成功 
} 
if(find(ciss.begin(),ciss.end(),"Person") != ciss.end()) 
{
      //失败,原因如上描述 
} 

优先使用关联容器自己的比较函数(一般都是less函数) 

 

2.为包含指针的关联容器指定比较类型

struct StringPtrLess
{
	bool operator()(const string *ps1, const string* ps2)
	{
		return *ps1 < *ps2;	
	}
}

using StringPtrSet = set<string*, StringPtrLess>;

StringPtrSet ss;
using iter = StringPtrSet::const_iterator;
for(iter i = ss.begin(); i != ss.end(); i++)
{
	cout << **i <<endl;
}

  

posted @ 2021-10-31 09:35  Kiris  阅读(34)  评论(0编辑  收藏  举报