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; }