fork download
  1. #include <iostream>
  2. #include<map>
  3. #include<iterator>
  4. #include<utility>
  5. using namespace std;
  6.  
  7. void printMap(map<string,int> &fm){
  8. cout << fm.size() << endl;
  9. //map<string,int>::iterator it;
  10. for(auto it = fm.begin();it != fm.end();++it){
  11. //cout << (*it).first << "-" << (*it).second << endl;
  12. cout << it->first << "-" << it->second << endl;
  13. }
  14. }
  15. int main() {
  16. //basic initialization.
  17. map<string,int> m1;
  18. m1["date"] = 22; //O(log(n));n = current size.
  19. m1["month"] = 05;
  20. m1["year"] = 2004;
  21. printMap(m1);
  22.  
  23. //initializing a map using pair,using insert():
  24. map<string,int> m2;
  25. m2.insert(make_pair("date",22));
  26. m2.insert({"month",05});
  27. printMap(m2);
  28. m2["day"]; //inserts an empty string to "day" key.
  29. printMap(m2);
  30.  
  31. //find(key):return the iterator for a specific key in the map.
  32. //if the key doesnt exist, it will return the iterator for end().
  33. auto it2 = m2.find("date");
  34. cout << (*it2).second << endl;
  35. auto it3 = m2.find("month");
  36. if(it3 == m2.end())
  37. cout << "no such key\n";
  38. else
  39. cout << it3->second << endl;
  40. return 0;
  41. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
3
date-22
month-5
year-2004
2
date-22
month-5
3
date-22
day-0
month-5
22
5