追查源码 , 我发现他是用的find方法 , 将结果跟尾迭代器比较 , 如果不等于尾迭代器就是找到了 , 返回1;反之就是没找到 , 返回0 。
find(const _Key& __k) const { const_iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k); return (__j == end() || _M_impl._M_key_compare(__k, _S_key(__j._M_node))) ? end() : __j; }
find获取元素迭代器/* * 用find函数寻找元素 , * */void find2(set<int> s ){ if (s.find(4)!= s.end() ) { cout << "元素4存在"<<endl; }else{ cout << "元素4不存在"; } if (s.find(8)!= s.end() ) { cout << "元素8存在"<<endl; }else{ cout << "元素8不存在"; }}
而底层是调用的不带const标的find函数 , 函数体是一样的!而其中的核心逻辑就是用_M_lower_bound函数查找来确定位置 。
_M_lower_bound(_Link_type __x, _Base_ptr __y, const _Key &__k){ while (__x != 0) { if (!_M_impl._M_key_compare(_S_key(__x), __k)) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); } return iterator(__y); }
比较函数key排序map中默认就是使用key排序的 , 自动按照key的大小 , 增序存储 , 这也是作为key的类型必须能够进行 < 运算比
较的原因 。
首先看一眼map模板的定义 , 重点看下第三个参数:class Compare = less<Key> 。
template < class Key , class T , class Compare = less<Key> , class Allocator = allocator<pair<const Key , T> > > class map;
与less相对的还有greater , 都是STL里面的一个函数对象 , 那么什么是函数对象呢?
函数对象:即调用操作符的类 , 其对象常称为函数对象(function object) , 它们是行为类似函数的对象 。表现出一个函数的特征 , 就是通过“对象名+(参数列表)”的方式使用一个 类 , 其实质是对operator()操作符的重载 。
具体的例子可以去看另一篇文章:Cpp浅析系列-STL之set , 这里就不赘述了 。
value排序逻辑上是先转为vector数组 , 接着将数组用指定的规则重新排序得到排序好的结果 。至于是否用排序好的数组去转换为map对象则是看要求了 。
bool Special(pair<string, int> a, pair<string, int> b) { return a.second < b.second;//从小到大排序}void specialCompare() { // 初始map集合 map<string, int> m; m["a"] = 2; m["b"] = 3; m["c"] = 1; // 转为vector集合 vector<pair<string, int> > demo(m.begin(), m.end()); for (auto it = demo.begin(); it != demo.end(); ++it) { cout << (*it).first << " " << (*it).second << endl; } cout << endl; // 排序后查看效果 sort(demo.begin(), demo.end(), Special); for (auto it = demo.begin(); it != demo.end(); ++it) { cout << (*it).first << " " << (*it).second << endl; } cout << endl; // 转换为新的map集合 , 区别就是前后类型反了 。 map<int, string> m2; for (vector<pair<string, int> >::iterator it = demo.begin(); it != demo.end(); ++it){ m2[(*it).second]=(*it).first; } map<int, string>::iterator iter; for (iter = m2.begin(); iter != m2.end(); iter++) { cout << iter->first << ' ' << iter->second << endl; }}//a 2// b 3// c 1//// c 1// a 2// b 3//// 1 c// 2 a// 3 b
推荐阅读
- 惠普战系列台式机评测 惠普台式电脑怎么样
- 沈月|盘点“致我们系列”六大主演现状,5人成了流量演员,1人不再拍戏
- 战神|推翻一切的新《战神》系列,续作还能带来惊喜吗?
- 美剧|网飞出品的6部黄暴系列美剧,一口气看完真过瘾
- 生化危机全系列剧情解析 生化危机电影剧情
- 美剧系列剧哪部好看,看看有什么好看的美剧-
- 姐姐|网络美女系列;乃木坂最漂亮的姐姐–卫藤美彩
- 为什么猎鹰系列发展迅速
- 主持人|“重启”系列续作电影《重启之深渊疑冢》今日上线 高能探险精彩升级
- 雅诗兰黛红石榴系列合适年纪是什么? 雅诗兰黛红石榴系列