在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1.#include <iostream> 1.#include <map> 2.using namespace std; 3. 4. 5.int main() 6.{ 7. map<int, int> test_map; 8. test_map[1] = 1; 9. test_map[2] = 2; 10. test_map[3] = 3; 11. test_map[4] = 4; 12. 13. for( std::map<int, int>::iterator iter = test_map.begin(); 14. iter != test_map.end(); ++ iter ) 15. { 16. cout << iter->first << " " << iter->second << endl; 17. } 18. 19. int count = 0; 20. 21. // delete the element 22. for( std::map<int, int>::iterator iter = test_map.begin(); 23. iter != test_map.end(); ) 24. { 25. std::map<int, int>::iterator it_back = iter; 26. bool is_first_element = false; 27. if(it_back != test_map.begin()) 28. it_back --; 29. else 30. is_first_element = true; 31. 32. // delete the element that matches the specific condition 33. if( iter->first % 2 == 0) 34. { 35. test_map.erase(iter); 36. 37. if(is_first_element) 38. iter = test_map.begin(); 39. else 40. iter = ++ it_back; 41. }else iter ++; 42. 43. count ++; 44. } 45. 46. cout << "use count:" << count << endl; 48. cout << "after delete " << endl; 49. 50. for( std::map<int, int>::iterator iter = test_map.begin(); 51. iter != test_map.end(); ++ iter) 52. { 53. cout << iter->first << " " << iter->second << endl; 54. } 55. 56. system("pause"); 7. return 0; 58. 59.} 运行结果 1 1 2 2 3 3 4 4 use count:4 after delete 1 1 3 3
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论