C++ Map学习 | Word count: 520 | Reading time: 3min
Demo 展示了如何在Map中绑定一个类指针,包括类的申请和释放,同样也展示了嵌套的Map的使用。
demo.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 #include <iostream> #include <map> using namespace std; class SocKet{ public: string name; int id ; void pri_name() { cout << name << endl; } void pri_id() { cout << id << endl; } }; int main(){ map<int , SocKet*> socket_id_map; string tmp_name; map<int , map<string, string>> total_cache_buf_map; map<string, string> cache_buf_map; string iter_name; int iter_pid; for (int i = 0 ; i < 3 ; i++) { tmp_name.clear(); socket_id_map[i] = new SocKet; tmp_name = "Socket" + to_string(i); socket_id_map[i]->name = tmp_name; socket_id_map[i]->id = i; } for (auto iter = socket_id_map.begin(); iter != socket_id_map.end(); ++iter) { iter_name = iter->second->name; iter_pid = iter->second->id ; cout << iter_name << endl; cout << iter_pid << endl; cout << endl; iter->second->pri_name(); iter->second->pri_id(); cout << endl; delete iter->second; iter->second = NULL ; socket_id_map.erase(iter); } for (int i = 0 ; i < 3 ; i++) { total_cache_buf_map[i][to_string(i)] = "package" + to_string(i); } for (auto re_iter = total_cache_buf_map.begin(); re_iter != total_cache_buf_map.end(); ++re_iter) { if (re_iter->first == 1 ) { auto re_pack_iter = re_iter->second.find("1" ); if (re_pack_iter == re_iter->second.end()) { cout << "______________________" << endl; } re_iter->second.erase("1" ); } } total_cache_buf_map[2 ]["xiao hong" ] = "xiao ming" ; for (auto iter_total = total_cache_buf_map.begin(); iter_total != total_cache_buf_map.end(); ++iter_total) { for (auto iter_package = iter_total->second.begin(); iter_package != iter_total->second.end(); ++iter_package) { cout << iter_total->first << " : " << iter_package->first << " : " << iter_package->second << endl; } } return 0 ; }
thread.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 #include <thread> #include <iostream> #include <unistd.h> using namespace std; static const int numthread = 10 ;void show(int i){ while (1 ) { sleep(5 ); cout << "hello wolrd" <<i<< endl; } } int main(){ thread *th_ptr = nullptr; th_ptr = new thread[numthread]; for (int i = 0 ; i < numthread;i++) { th_ptr[i] = thread(show,i); } for (int i = 0 ; i < numthread; i++) { th_ptr[i].detach(); } while (1 ) { sleep(2 ); } return 0 ; }