zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    C#基础篇十小练习
    C#基础篇九OOP属性结构枚举
    C#基础篇八构造函数和面向对象思想
    C#基础篇七类和静态成员
    C#基础篇六飞行棋
    C#基础篇五值类型和引用类型
    数据与地址的自动给定---基于状态机
    SPI 核的寄存器空间
    mig_7series DDR控制器的配置
    关于zynq7 中MIO的理解
  • 原文地址:https://www.cnblogs.com/tid-think/p/10766186.html
Copyright © 2011-2022 走看看