码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-09 00:41:29      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

一、等价与相等的简述

  在容器中,等价并不是相等。为什么要提等价与相等呢?因为泛型算法中的find等用于比较的是相等,即以operator==为基础,而容器成员函数的比较是以operator<为基础,所以区分二者很重要。

 1、相等

  这个很好理解,operator==返回真即代表二者相等。注:二者相等只是函数返回真,具体规则程序员可以指定的。

 2、等价

  等价关系是以“在已排序的区间中对象值的相对顺序”为基础的(Effective STL).set map排序时,就是默认的使用这种方式。即每一个都不在另一个前面。代码示意为:

  

!(w1 < w1) && ! (w2 < w1)

 3、一个忽略大小写的set程序实现:其中,忽略大小写的set执行的比较类型。

  

 1 #include <string>
 2 
 3 struct CIStringCompare{
 4     bool operator()(const std::string& lhs, const std::string& rhs) const
 5     {
 6         int flag =  ciStringCompare(lhs, rhs);
 7         if (flag < 0) return true;
 8         else return false;
 9     }
10     int ciStringCompare(const std::string &lhs, const std::string &rhs) const
11     {
12         return _stricmp(lhs.c_str(), rhs.c_str());
13     }
14 };
 1 #include <set>
 2 #include <iostream>
 3 #include "CIStringCompare.h"
 4 #include <algorithm>
 5 int main()
 6 {
 7     // 区分大小写
 8     std::set<std::string> oriset;
 9     oriset.insert("FuckC++");
10     oriset.insert("fuckc++");
11 
12     // 不分大小写
13     std::set<std::string, CIStringCompare> testset;
14     testset.insert("FuckC++");
15     testset.insert("fuckc++");
16 
17     std::cout << "区分大小写" << std::endl;
18     for_each(oriset.begin(), oriset.end(), [](const std::string& s)->void{std::cout << s << std::endl; });
19 
20     std::cout << "不区分大小写" << std::endl;
21     for_each(testset.begin(), testset.end(), [](const std::string& s)->void{std::cout << s << std::endl; });
22     return 0;
23 }

  显然,执行结果如下:

                            技术分享

二、待续

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

标签:

原文地址:http://www.cnblogs.com/tntboom/p/4562175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!