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

代码 

#include 
#include 
#include 
class ResID {
public:
    using SP = std::shared_ptr;

    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;

    // 自定义比较器
    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()(lhs->type()) ^ std::hash()(lhs->id());
        }
    };
    template
    using UMap
        = std::unordered_map;
		
private:
    std::string m_id;
    std::string m_type;
};
示例

class Data{
public:
int value;
};


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

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

C++智能指针配合STL模板类_第1张图片C++智能指针配合STL模板类_第2张图片

你可能感兴趣的:(C++,教程,c++,开发语言,stl)