linux c++ map 的key是结构体 typedef struct data unsigned int run_time; HelloWorldPtr clientPtr; stdstring clientName; stdstring clientCbAddr; tag_ClientCBS;value 是int 怎么实现增、删查给出实现代码
要实现对于 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;
int main() {
std::map<tag_ClientCBS, int> 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;
}
在上面的示例中,我们首先定义了一个 std::map 对象 myMap,键的类型是 tag_ClientCBS 结构体,值的类型是 int。然后,我们使用 myMap[key] = value 语法向 std::map 中添加元素,其中 key 是 tag_ClientCBS 结构体的实例,value 是 int 值。我们也可以使用 myMap.erase(key) 删除指定键的元素。最后,我们使用 myMap.find(key) 查找指定键的元素,返回一个迭代器,通过判断迭代器是否等于 myMap.end() 来判断是否找到了对应的值。
原文地址: http://www.cveoy.top/t/topic/i1YR 著作权归作者所有。请勿转载和采集!