C++ STL map key是自定义结构体或类

/// @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 覆盖


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值