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


    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;
    }
  • 相关阅读:
    3.约束及修改数据表
    RSA总结
    消息队列面试官爱问的问题(一)
    Maven模块化开发
    系统初始化脚本和检查初始化结果脚本(centos7)
    kubectl 命令自动补全
    Kubernetes1.13.1部署Kuberneted-dashboard v1.10.1
    python实现连接MySQL、Redis并获取数据
    shell 脚本实现退点输出
    理论经典:TCP协议的3次握手与4次挥手过程详解
  • 原文地址:https://www.cnblogs.com/tid-think/p/10766186.html
Copyright © 2020-2023  润新知