C++ map 使用结构体作为键的增删改查方法

在 C++ 中,可以使用 std::map 来存储键值对。当需要使用结构体作为键时,可以自定义比较函数或者重载运算符来实现。

以下代码示例展示了如何使用 std::map 存储键为结构体 tag_ClientCBS,值为 int 的数据,并演示了增、删、查的操作。

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

// 定义结构体
typedef struct 
{
    unsigned int run_time;
    int clientPtr;
    std::string clientName;
    std::string clientCbAddr;
} tag_ClientCBS;

// 自定义比较函数
struct CompareTagClientCBS {
    bool operator()(const tag_ClientCBS& lhs, const tag_ClientCBS& rhs) const {
        if (lhs.run_time != rhs.run_time) {
            return lhs.run_time < rhs.run_time;
        }
        if (lhs.clientPtr != rhs.clientPtr) {
            return lhs.clientPtr < rhs.clientPtr;
        }
        if (lhs.clientName != rhs.clientName) {
            return lhs.clientName < rhs.clientName;
        }
        return lhs.clientCbAddr < rhs.clientCbAddr;
    }
};

int main() {
    // 使用自定义比较函数创建 map
    std::map<tag_ClientCBS, int, CompareTagClientCBS> myMap;

    // 添加元素
    tag_ClientCBS key1 = { 100, 1, 'client1', 'address1' };
    myMap[key1] = 10;

    tag_ClientCBS key2 = { 200, 2, 'client2', 'address2' };
    myMap[key2] = 20;

    // 删除元素
    myMap.erase(key1);

    // 查找元素
    tag_ClientCBS key3 = { 200, 2, 'client2', 'address2' };
    auto it = myMap.find(key3);
    if (it != myMap.end()) {
        std::cout << 'Value found: ' << it->second << std::endl;
    } else {
        std::cout << 'Value not found' << std::endl;
    }

    return 0;
}

代码说明:

  1. 自定义比较函数: 为了能够使用结构体作为 std::map 的键,需要自定义一个比较函数 CompareTagClientCBS。该函数接受两个 tag_ClientCBS 结构体作为参数,并根据结构体成员变量的值进行比较,返回 true 表示小于,false 表示大于等于。
  2. 创建 map: 在创建 std::map 对象时,需要将自定义的比较函数作为第三个模板参数传入。
  3. 增删改查: 使用 [] 运算符添加元素,使用 erase() 方法删除元素,使用 find() 方法查找元素。

通过以上步骤,就可以在 C++ 中使用 std::map 存储键为结构体的数据了。

C++ map 使用结构体作为键的增删改查方法

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

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