C++ STL map key是自定义结构体或类
2015-11-02 13:14
411 查看
/// @file 1.cpp /// @brief /// @author EastonWoo /// 0.01 /// @date 2015-11-02 #include <stdio.h> #include <unistd.h> #include <semaphore.h> #include <pthread.h> #include <string> #include <map> class CKey{ public: CKey(std::string str1, std::string str2) { this->str1 = str1; this->str2 = str2; } public: std::string str1; std::string str2; public: bool operator<(const CKey & ct) const // 两个const是必需的。 { if (str1 < ct.str1) { return true; } else if (str1 == ct.str1) { if ( str2 < ct.str2 ) { return true; } } return false; } }; int main(int argc, const char *argv[]) { std::map<CKey, std::string> _map; CKey key1("11", "12"); // 被key6覆盖 CKey key6("11", "12"); CKey key5("23", "12"); CKey key7("22", "22"); CKey key2("21", "22"); CKey key3("21", "23"); CKey key4("21", "21"); _map[key1] = "hello"; _map[key2] = "world1"; _map[key3] = "world2"; _map[key4] = "world3"; _map[key5] = "world4"; _map[key6] = "world5"; _map[key7] = "world6"; for(auto it = _map.begin(); it != _map.end(); ++it) { printf("[%s:%s]it->second = %s\n", it->first.str1.c_str(), it->first.str2.c_str(), it->second.c_str()); } return 0; } // 编译,打印 // tmp-> g++ 1.cpp -std=c++0x && ./a.out // [11:12]it->second = world5 // [21:21]it->second = world3 // [21:22]it->second = world1 // [21:23]it->second = world2 // [22:22]it->second = world6 // [23:12]it->second = world4 // tmp-> // // // 结果: key5 > key7 > key3 > key2 > key4 > key6 = key1 // key1 被 key6 覆盖
相关文章推荐
- 高级C语言教程
- effective c++ 将成员变量声明为private
- C++的for语句详解
- c++ volatile关键字
- 详解C++中命名空间的意义和用法
- 【C/C++学院】0823-静态联合编译与动态联合编译/父类指针子类指针释放/虚函数/纯虚函数概念以及虚析构函数/抽象类与纯虚函数以及应用/虚函数原理/虚函数分层以及异质链表/类模板的概念以及应用
- C++11 标准新特性:Defaulted 和 Deleted 函数
- c语言学习之基础知识点介绍(十):内存空间模型、地址解释及指针变量
- 今日学习札记——C++程序设计1(11-02)
- C++标准库阅读摘要
- 3.2 ACM输入输出--多组测试用例--C、C++
- ——黑马程序员——C语言中的指针(二)
- C语言第五章 语句
- C++11 多线程下生产者消费者模型详解
- 做c语言的码农专业发展方向
- C语言设计模式
- C++ 初始化列表
- 外部exe程序启动CAD并且自动加载CAD的ARX程序的过程
- OC语言中BOOL 和 bool 区别
- 《C++ primer》英文第五版阅读笔记(七)——定义自己的数据类型