C++ map 使用自定义结构体作为 key

在 C++ 中,可以使用自定义结构体作为 std::map 的 key。

本文将以 tag_ClientCBS 结构体为例,详细介绍如何实现该功能。

'tag_ClientCBS' 结构体

typedef struct 
{
    HelloWorldPtr clientPtr;
    std::string   clientName;
    std::string   clientCbAddr;
}tag_ClientCBS;

自定义比较函数

为了将 tag_ClientCBS 结构体作为 map 的 key,首先需要定义一个比较函数,用于比较两个 tag_ClientCBS 结构体是否相等。

struct CompareClientCBS {
    bool operator()(const tag_ClientCBS& cbs1, const tag_ClientCBS& cbs2) const {
        if (cbs1.clientPtr == cbs2.clientPtr &&
            cbs1.clientName == cbs2.clientName &&
            cbs1.clientCbAddr == cbs2.clientCbAddr) {
            return true;
        }
        return false;
    }
};

声明 map

然后,在声明 std::map 时,指定该比较函数作为 key 的比较方式:

std::map<tag_ClientCBS, ValueType, CompareClientCBS> myMap;

其中,ValueType 是你想要存储的值的类型。

通过以上步骤,就可以在 C++ 中使用自定义结构体作为 std::map 的 key 了。

C++ map 使用自定义结构体作为 key

原文地址: https://www.cveoy.top/t/topic/fdHP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录