Linux C++ 使用结构体作为 std::map 的键,C++98 标准示例

本文介绍如何在 Linux C++ 中使用结构体作为 std::map 的键,并提供使用 'clientName' 和 'clientCbAddr' 作为键的示例。该示例使用 C++98 标准,并展示了自定义比较函数的使用方法。

结构体定义

首先,定义一个结构体 tag_ClientCBS,它包含 'clientName' 和 'clientCbAddr' 两个字段,以及其他数据:

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

自定义比较函数

为了使结构体能够作为 std::map 的键,需要定义一个自定义比较函数。该函数将比较两个 tag_ClientCBS 结构体的 'clientName' 和 'clientCbAddr' 字段:

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;
    }
};

使用示例

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

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

// ... 结构体定义和比较函数定义 ...

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 C++ 中使用结构体作为 std::map 的键,并提供了使用 C++98 标准的示例。通过定义自定义比较函数,可以将结构体中的特定字段作为键进行比较,从而实现灵活的数据存储和检索。

Linux C++ 使用结构体作为 std::map 的键,C++98 标准示例

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

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