代码
#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);
创作不易,小小的支持一下吧!
![]()
![]()