Effective STL学习笔记-条款23
来源:互联网 发布:类似米赚的软件 编辑:程序博客网 时间:2024/06/05 19:33
考虑使用有序vector代替关联容器
直接进入主题,为什么会考虑使用vector代替关联容器呢,可能有这样的场景,一对关联的数据,而时使用时要求数据查找速度很快。
当然我们必须知道有序的vector的缺点就是他必须保持有序,一个新item插入可能造成其他元素的移动。所以这种场景可能在几乎不插入和删除时考虑。
一个例子:
using Pair = pair<int, string>;using VecPair = vector<Pair>; //vector存储了key=int,value=string
//我们对vector查找 或者排序时 肯定要实现相应的仿函数、或者lambda方程式class VecPairCompare{public: //排序比较函数 bool operator()(const Pair& lhs, const Pair& rhs) const { return keyLess(lhs.first, rhs.first); } //查找比较函数 type1 bool operator()(const Pair& lhs, const Pair::first_type& key) const { return keyLess(lhs.first, key); } //查找比较函数 type2 bool operator()(const Pair::first_type& key, const Pair& rhs) const { return keyLess(key, rhs.first); }private: bool keyLess(const Pair::first_type& lhs, const Pair::first_type& rhs) const { return lhs < rhs; }};
使用如下:
VecPair vec; //测试数据 vec.push_back(std::make_pair<int, string>(3, "abc")); vec.push_back(std::make_pair<int, string>(1, "efg")); vec.push_back(std::make_pair<int, string>(2, "hij")); //我们可以看到数据是正常放置 for (auto tempPair : vec) { cout << "O:" << tempPair.first << " " << tempPair.second << endl; } cout << endl; //按照key的大小进行 排序 std::sort(vec.begin(), vec.end(), VecPairCompare()); for (auto tempPair : vec) { cout << "O:" << tempPair.first << " " << tempPair.second << endl; } //查找 if (binary_search(vec.begin(), vec.end(), 1, VecPairCompare())) { cout << "found key 1" << endl; }
打印结果:
个人认为pair是非常好用的,他表示数据之间的关联性,套用vector保证数据的顺序。
阅读全文
0 0
- Effective STL学习笔记-条款23
- 【Effective STL】条款1-5学习笔记
- 【Effective STL】条款6-12学习笔记
- 【Effective STL】条款13-18学习笔记
- Effective STL学习笔记-条款1
- Effective STL学习笔记-条款7
- Effective STL学习笔记-条款8-9
- Effective STL学习笔记-条款13|14
- Effective STL学习笔记-条款19
- Effective STL学习笔记-条款20
- Effective STL学习笔记-条款21
- Effective STL学习笔记-条款24
- Effective STL学习笔记-条款30
- Effective STL学习笔记-条款31
- Effective STL学习笔记-条款32
- Effective STL学习笔记-条款33
- Effective STL学习笔记-条款34
- Effective STL学习笔记-条款36
- SpringCloud(第 026 篇)简单异构系统之 nodejs 微服务
- S3C2440存储器扩展研究——剖析nWE, nWBE, nBE间关系
- Servlet学习笔记
- TCP/IP学习笔记(11)-TCP交互数据流,成块数据流
- 仙人掌学习笔记
- Effective STL学习笔记-条款23
- Linux下编译ffmpeg及其依赖库
- Java设计模式之工厂模式
- [BZOJ1095]Hide 捉迷藏--括号序列&&线段树
- .dll文件和.so文件
- neuq 1147: 尼科彻斯定理
- 系统定制修改之修改 chrome 浏览器默认主页为指定网址
- Nginx+tomcat配置集群负载均衡
- js--排序算法--选择排序