下面是一个使用clientName和clientCbAddr作为键的std::map的示例:

#include <iostream>
#include <map>
#include <string>

typedef struct 
{
    unsigned int run_time;
    void* clientPtr;
    std::string clientName;
    std::string clientCbAddr;
} tag_ClientCBS;

struct CompareKeys
{
    bool operator()(const tag_ClientCBS& lhs, const tag_ClientCBS& rhs) const
    {
        if (lhs.clientName != rhs.clientName)
            return lhs.clientName < rhs.clientName;
        return lhs.clientCbAddr < rhs.clientCbAddr;
    }
};

int main()
{
    std::map<tag_ClientCBS, int, CompareKeys> myMap;

    // 添加元素
    tag_ClientCBS client1 = { 0, nullptr, "client1", "addr1" };
    myMap[client1] = 1;

    tag_ClientCBS client2 = { 0, nullptr, "client2", "addr2" };
    myMap[client2] = 2;

    tag_ClientCBS client3 = { 0, nullptr, "client1", "addr3" };
    myMap[client3] = 3;

    // 遍历map
    for (std::map<tag_ClientCBS, int, CompareKeys>::iterator it = myMap.begin(); it != myMap.end(); ++it)
    {
        std::cout << "Key: " << it->first.clientName << ", " << it->first.clientCbAddr << ", Value: " << it->second << std::endl;
    }

    return 0;
}

该示例定义了一个tag_ClientCBS结构体作为键,并使用clientName和clientCbAddr进行比较。CompareKeys结构体定义了一个用于比较键的函数对象。使用std::map<tag_ClientCBS, int, CompareKeys>定义了一个std::map,其中键类型为tag_ClientCBS,值类型为int,比较函数为CompareKeys。然后,示例添加了几个元素到myMap中,并通过迭代器遍历输出了键值对。

linux cc++ map使用结构体所为key	typedef struct 			 data 		unsigned int run_time; HelloWorldPtr clientPtr;		stdstring clientName;		stdstring clientCbAddr;	tag_ClientCBS;c++使用c++98标准使用clientName、c

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

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