C++ map操作——插入、查找、遍历

本文详细介绍了C++中map容器的使用方法,包括初始化、遍历、查找、删除和插入等操作。通过具体代码示例,展示了如何创建map,如何进行元素的增删查改,以及如何处理重复键的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++ map 操作学习

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

using namespace std;

typedef struct clientInfo_t {
    int fd;
    long timeOut;
}clientInfo_t;

int main(int argc, char **argv)
{

    map<int, clientInfo_t> clientMap = {};
    clientInfo_t tmpInfo = {};

    /*map init*/
    for(int i = 3; i < 20; ++i) {
        tmpInfo.fd = i;
        tmpInfo.timeOut = -1;
        //clientMap.insert(pair<int, clientInfo_t>(i, tmpInfo));
        clientMap[i] =  tmpInfo;
    }

    /*map trave*/
    for (auto m = clientMap.begin(); m != clientMap.end(); ++m) {
        cout <<"client fd = "<< m->second.fd << " timeOut = " <<m->second.timeOut<<endl;
    }
    
    tmpInfo.fd = 15;
    tmpInfo.timeOut = -1;
    /*map find*/
    auto m = clientMap.find(15);
    if (m != clientMap.end() ) {
        m->second.timeOut = 0;
        cout <<"map find fd = " <<m->second.fd<<endl;;
    }

    /*map erase*/
    for (auto m = clientMap.begin(); m != clientMap.end(); /*do nothing*/) {
        if(m->second.fd % 2 == 0) {
            m = clientMap.erase(m);
        }
        else {
            ++m;
        }
    }
    
    for (auto m = clientMap.begin(); m != clientMap.end(); ++m) {
        cout <<"client fd = "<< m->second.fd << " timeOut = " <<m->second.timeOut<<endl;
    }

    /*map insert*/
    tmpInfo.fd = 25;
    tmpInfo.timeOut = 25;
    /*this will replace key 13 use new value*/
    clientMap[13] = tmpInfo;

    /*new insert*/
    clientMap[23] = tmpInfo;

    /*this will insert failed, becase key 17  exist*/
    clientMap.insert(pair<int, clientInfo_t>(17, tmpInfo));

    /*only not exist key can insert success*/
    clientMap.insert(pair<int, clientInfo_t>(27, tmpInfo));
    cout <<"===insert element end======"<<endl;
    
    for (auto m = clientMap.begin(); m != clientMap.end(); ++m) {
        cout <<"client fd = "<< m->second.fd << " timeOut = " <<m->second.timeOut<<endl;
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/tid-think/p/10766186.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值