1. //插入元素 //四种插入方法比较
  2. void display()
  3. {
  4. map<int,string> m;
  5. pair<map<int,string>::iterator,bool> pair1 ,pair2,pair3;
  6. //1.方法
  7. pair1 = m.insert(pair<int,string>(1,"teacher01"));
  8. pair2 = m.insert(pair<int,string>(2,"teacher02"));
  9. pair3 = m.insert(pair<int,string>(2,"teacher02"));
  10. if (pair2.second)
  11. {
  12. cout<<"2 teacher02插入成功"<<endl;
  13. cout<<pair2.first->first<<":"<<pair2.second<<endl;
  14. }
  15. else
  16. {
  17. cout<<"2 teacher02插入失败"<<endl;
  18. cout<<pair2.first->first<<":"<<pair2.second<<endl;
  19. }
  20. if (pair3.second)
  21. {
  22. cout<<"2 teacher02插入成功"<<endl;
  23. cout<<pair3.first->first<<":"<<pair3.second<<endl;
  24. }
  25. else
  26. {
  27. cout<<"2 teacher02插入失败"<<endl;
  28. cout<<pair3.first->first<<":"<<pair3.second<<endl;
  29. }
  30. //2.方法
  31. m.insert(make_pair(3,"teacher03"));
  32. m.insert(make_pair(4,"teacher04"));
  33. //3.方法
  34. m.insert(map<int,string>::value_type(5,"teacher05"));
  35. m.insert(map<int,string>::value_type(6,"teacher06"));
  36. //4. 如果key相等 会修改对应的value
  37. m[7] = "teacher07";
  38. m[8] = "teacher08";
  39. m[0] = "teacher09";
  40. m[0] = "teacher00";
  41. //遍历
  42. for (map<int,string>::iterator it = m.begin();it!=m.end();it++)
  43. {
  44. cout<<(*it).first<<endl;
  45. cout<<(*it).second<<endl;
  46. }
  47. while (!m.empty())
  48. {
  49. map<int,string>::iterator it = m.begin();
  50. cout<<it->first<<"\t"<<it->second<<endl;
  51. m.erase(it);
  52. }
  53. }

                  </div>
</article>
Logo

云原生社区为您提供最前沿的新闻资讯和知识内容

更多推荐