C++智能指针配合STL模板类

5 篇文章 0 订阅
代码 

#include <unordered_map>
#include <set>
#include <memory>
class ResID {
public:
    using SP = std::shared_ptr<ResID>;

    ResID() = default;
    ResID(const std::string& id, const std::string& type)
        : m_id(id)
        , m_type(type)
    {
    }

public:
    ~ResID() = default;
    bool isValid() const { return !m_id.empty() && !m_type.empty(); };
    bool isEqual(const ResID& other) const
    {
        return m_id == other.m_id && m_type == other.m_type;
    }
    std::string type() const { return m_type; }
    std::string id() const { return m_id; }
    void setType(const std::string& type) { m_type = type; }
    void setId(const std::string& id) { m_id = id; }

    // 自定义比较器
    struct Compare {
        bool operator()(ResID::SP lhs, ResID::SP rhs) const
        {
            // 根据`value`成员变量进行比较
            return std::tuple(lhs->type(), lhs->id()) < std::tuple(lhs->type(), lhs->id());
        }
    };
    using Set = std::set<ResID::SP, ResID::Compare>;

    // 自定义比较器
    struct Equal {
        bool operator()(ResID::SP lhs, ResID::SP rhs) const
        {
            return lhs->isEqual(*rhs);
        }
    };

    // 自定义比较器
    struct Hash {
        size_t operator()(ResID::SP lhs) const
        {
            return std::hash<std::string>()(lhs->type()) ^ std::hash<std::string>()(lhs->id());
        }
    };
    template<class T>
    using UMap
        = std::unordered_map<ResID::SP, T, ResID::Hash, ResID::Equal>;
		
private:
    std::string m_id;
    std::string m_type;
};
示例

class Data{
public:
int value;
};


auto resID = std::make_shared<ResID>("id", "type");
auto resID2 = std::make_shared<ResID>("id2", "type2");
ResID<Data>::UMap uMap;
uMap.emplace(resID, {});
uMap.emplace(resID2, {});
uMap.emplace(resID, {});
assert(uMap.size() == 2);

创作不易,小小的支持一下吧!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码力码力我爱你

创作不易,小小的支持一下吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值