首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

stl的set怎么判断2个值相等的?(唯一性)

2012-04-23 
stl的set如何判断2个值相等的?(唯一性)我知道是根据他的比较函数来实现唯一性的,但更进一步就不太了解了,

stl的set如何判断2个值相等的?(唯一性)
我知道是根据他的比较函数来实现唯一性的,但更进一步就不太了解了,遇到以下情况不知道如何解决。
class City
{
public:
City(string cityName, int cost, string srcCityName)
{
this->cityName = cityName;
this->cost = cost;
this->srcCityName = srcCityName;
}
string cityName;
int cost;
string srcCityName;
};
/** 先不管第三个参数,我想根据第一个参数来实现唯一性【即第一个参数在set中不能重复】 */
/** 下面是我重写的比较函数 
 * 先比较第二个参数,如果第二个参数相同,则比较第一个参数【在比较方面我大概要实现这种功能】
 */
class CostCompare
{
public:
bool operator()(const City& left, const City& right)
{
return (left.cost < right.cost) || ((left.cost == right.cost)&&(left.cityName < right.cityName));
}
};

/** set */
set<City, CostCompare> openCityRoute;


以上就是主要代码了,可如果是按比较的内容来决定唯一性,那么这里判断是否唯一就是根据cityName和cost,2个值,当2个值相等时才认为这个要保存到set的值已经存在。  
但我想要的是,判断时,先判断cost,再判断cityName; 而唯一性则仅根据cityName是否相同来判断。

有什么方法可以做到???

[解决办法]
楼主 查了挺多资料的 下面这些应该能帮到你 你可以上网查下 strick weak ordering严格弱排序

下面是一篇严格弱排序的文章

http://blog.csdn.net/zyyoung/article/details/6062377

里面一句话:。问题猜测肯定是出在 operator < 这个函数上了,因为根据自己的 operator < 定义: {31, 41} < {31, 59} 返回值是 false , {31, 59} < {31, 41} 的返回值也是 false ,那么,由这两个比较能得出结论: {31, 41} == {31, 59} 

这是关于set比较器的说明:
Compare: Comparison class: A class that takes two arguments of the same type as the container elements and returns a bool. The expression comp(a,b), where comp is an object of this comparison class and a and b are elements of the container, shall return true if a is to be placed at an earlier position than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). This defaults to less<Key>, which returns the same as applying the less-than operator (a<b).
The set object uses this expression to determine the position of the elements in the container. All elements in a set container are ordered following this rule at all times.

这是set 关于insert 方法的部分说明:
Because set containers do not allow for duplicate values, the insertion operation checks for each element inserted whether another element exists already in the container with the same value, if so, the element is not inserted and -if the function returns a value- an iterator to it is returned.

热点排行