C++98 std::map实现键值对插入和遍历 - 基于自定义结构体的案例
C++98 std::map实现键值对插入和遍历 - 基于自定义结构体的案例
本文介绍如何使用C++98和std::map来存储和管理自定义结构体数据。我们将定义一个包含客户端名称和回调地址的结构体,并使用std::map来存储这些信息。
**代码实现:**cpp#include
// 定义结构体比较函数struct CompareClientCBS{ bool operator()(const tag_ClientCBS& c1, const tag_ClientCBS& c2) const { if (c1.clientName != c2.clientName) return c1.clientName < c2.clientName; return c1.clientCbAddr < c2.clientCbAddr; }};
// 定义客户端信息结构体typedef struct { std::string clientName; std::string clientCbAddr;} tag_ClientCBS;
// 定义全局的std::mapstatic std::map<tag_ClientCBS, int, CompareClientCBS> g_clientCBS_map;
// 插入客户端信息void InsertClientCBS(const std::string& clientName, const std::string& clientCbAddr){ tag_ClientCBS clientCBS; clientCBS.clientName = clientName; clientCBS.clientCbAddr = clientCbAddr; g_clientCBS_map[clientCBS] = 0; }
// 遍历并打印客户端信息void TraverseClientCBS(){ std::map<tag_ClientCBS, int, CompareClientCBS>::iterator it; for (it = g_clientCBS_map.begin(); it != g_clientCBS_map.end(); ++it) { std::cout << 'Client Name: ' << it->first.clientName << ', '; std::cout << 'Client Callback Address: ' << it->first.clientCbAddr << std::endl; }}
int main(){ InsertClientCBS('Client1', 'Address1'); InsertClientCBS('Client2', 'Address2'); InsertClientCBS('Client3', 'Address3'); TraverseClientCBS(); return 0;}
代码解释:
CompareClientCBS结构体: 定义了一个比较函数,用于在std::map中对tag_ClientCBS进行排序和比较。2.tag_ClientCBS结构体: 定义了客户端信息结构体,包含客户端名称和回调地址。3.g_clientCBS_map: 使用自定义的比较函数CompareClientCBS定义了一个全局的std::map对象,用于存储tag_ClientCBS结构体和对应的整数值。 4.InsertClientCBS函数: 接收客户端名称和回调地址作为参数,创建tag_ClientCBS对象并将其插入到g_clientCBS_map中。5.TraverseClientCBS函数: 遍历g_clientCBS_map并打印每个tag_ClientCBS对象的客户端名称和回调地址。6.main函数: 演示如何插入客户端信息并遍历打印。
总结:
这段代码展示了如何在C++98中使用 std::map 来存储和管理自定义结构体数据。通过自定义比较函数,我们可以根据实际需求对 std::map 中的元素进行排序和比较。
原文地址: https://www.cveoy.top/t/topic/fd5o 著作权归作者所有。请勿转载和采集!