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 << "size = " << 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. cout << endl;
  15. }
  16. int main() {
  17. //basic initialization.
  18. map<string,int> m1;
  19. m1["date"] = 22; //O(log(n));n = current size.
  20. m1["month"] = 05;
  21. m1["year"] = 2004;
  22. printMap(m1);
  23.  
  24. //initializing a map using pair,using insert():
  25. map<string,int> m2;
  26. m2.insert(make_pair("date",22));
  27. m2.insert({"month",05});
  28. printMap(m2);
  29. m2["day"]; //inserts an empty string to "day" key.
  30. printMap(m2);
  31.  
  32. //find(key):returns the iterator for a specific key in the map.
  33. //if the key doesnt exist, it will return the iterator for end().
  34. auto it2 = m2.find("date");
  35. cout << (*it2).second << endl;
  36. auto it3 = m2.find("month");
  37. if(it3 == m2.end())
  38. cout << "no such key\n";
  39. else
  40. cout << it3->second << endl; //-> works only for iterators.
  41.  
  42. //erase():erases a key. Can take the key or associated iterator as input.
  43. m2.erase("month"); //O(log(n)
  44. printMap(m2);
  45. //passing as iterator.
  46. auto it4 = m2.find("day");
  47. m2.erase(it4);
  48. printMap(m2);
  49. //passing an iterator that doesnt have a key.
  50. auto it5 = m2.find("arif"); //points to m2.end()
  51.  
  52. if (it5 != m2.end())
  53. m2.erase(it5);//a non-existent iterator cannot be passed to erase().
  54. printMap(m2);
  55.  
  56. //clear(): Clears the whole container.
  57. m2.clear();
  58. printMap(m2);
  59.  
  60. /*insert()'s TC also depends on the key. In a Red Black Tree, when a value is newly
  61.   inserted, its key initially goes through comparison with existent keys and then finds
  62.   the appropiate location to get inserted into.
  63.   *int -> O(log(n))
  64.   *string -> O(log(n) + s.size())
  65.   */
  66.  
  67.  
  68. /*
  69.   Problem: Given N strings, print unique strings in lexicographical order with their frequency.
  70.   N <= 10^5
  71.   |S| <= 100
  72.   */
  73. map<string,int> m;
  74. int N;
  75. cin >> N;
  76. for(int i=0;i<N;i++){
  77. string s;
  78. cin >> s;
  79. m[s];//m[s] initialized to zero, this line is just for illustration.
  80. m[s] = m[s] + 1;//updating frequency of all unique s.
  81. }
  82. printMap(m);
  83. //
  84.  
  85. return 0;
  86. }
  87. /*
  88. Here’s the updated summary of our chat about maps, including the handling of value overwriting with `insert()` and other methods:
  89.  
  90. ### Summary of Our Chat About Maps
  91.  
  92. 1. **Normal Maps with String Keys**:
  93.   - Keys in maps (dictionaries) can be strings, allowing for dynamic access and organization of values.
  94.   - Accessing values is done using string keys, which can be dynamically assigned.
  95.  
  96.   ```cpp
  97.   #include <iostream>
  98.   #include <map>
  99.   #include <string>
  100.  
  101.   int main() {
  102.   std::map<std::string, int> myMap;
  103.   myMap["apple"] = 1;
  104.   myMap["banana"] = 2;
  105.   myMap["cherry"] = 3;
  106.  
  107.   for (const auto& pair : myMap) {
  108.   std::cout << pair.first << " " << pair.second << std::endl;
  109.   }
  110.   return 0;
  111.   }
  112.   ```
  113.  
  114.   **Output**:
  115.   ```
  116.   apple 1
  117.   banana 2
  118.   cherry 3
  119.   ```
  120.  
  121. 2. **Sorting Behavior**:
  122.   - In **`std::map`**, keys are automatically sorted in ascending lexicographical order.
  123.   - In **`std::unordered_map`**, there is no guaranteed order for the keys, and their order can appear random.
  124.  
  125.   ```cpp
  126.   #include <iostream>
  127.   #include <unordered_map>
  128.   #include <string>
  129.  
  130.   int main() {
  131.   std::unordered_map<std::string, int> myMap;
  132.   myMap["banana"] = 2;
  133.   myMap["apple"] = 1;
  134.   myMap["cherry"] = 3;
  135.  
  136.   for (const auto& pair : myMap) {
  137.   std::cout << pair.first << " " << pair.second << std::endl;
  138.   }
  139.   return 0;
  140.   }
  141.   ```
  142.  
  143.   **Output** (order may vary):
  144.   ```
  145.   banana 2
  146.   cherry 3
  147.   apple 1
  148.   ```
  149.  
  150. 3. **Lexicographical Sorting**:
  151.   - Lexicographical order sorts keys based on alphabetical character comparison, similar to how words are arranged in a dictionary.
  152.   - The sorting process considers only the keys, independent of their associated values.
  153.  
  154. 4. **Sorting by Values**:
  155.   - To sort by values instead of keys, extract key-value pairs, sort them based on values, and print them.
  156.  
  157.   ```cpp
  158.   #include <iostream>
  159.   #include <unordered_map>
  160.   #include <vector>
  161.   #include <algorithm>
  162.   #include <string>
  163.  
  164.   int main() {
  165.   std::unordered_map<std::string, int> myMap;
  166.   myMap["banana"] = 2;
  167.   myMap["apple"] = 1;
  168.   myMap["cherry"] = 3;
  169.  
  170.   // Extract key-value pairs into a vector
  171.   std::vector<std::pair<std::string, int>> vec(myMap.begin(), myMap.end());
  172.  
  173.   // Sort by value
  174.   std::sort(vec.begin(), vec.end(), [](const auto& a, const auto& b) {
  175.   return a.second < b.second; // Compare based on the second element (value)
  176.   });
  177.  
  178.   // Print sorted key-value pairs
  179.   for (const auto& pair : vec) {
  180.   std::cout << pair.first << " " << pair.second << std::endl;
  181.   }
  182.  
  183.   return 0;
  184.   }
  185.   ```
  186.  
  187.   **Output of Sorting by Values**:
  188.   ```
  189.   apple 1
  190.   banana 2
  191.   cherry 3
  192.   ```
  193.  
  194. 5. **Handling Value Overwrites**:
  195.   - If you want to insert a value in a map but might overwrite an existing value, you can use different methods:
  196.  
  197.   **Using `operator[]`**:
  198.   ```cpp
  199.   myMap["banana"] = 5; // Overwriting the value of "banana"
  200.   ```
  201.   **insert() doesnt allow overwriting.
  202.   **Using `insert_or_assign()` (C++17 and later)**:
  203.   ```cpp
  204.   myMap.insert_or_assign("banana", 5); // Overwriting or inserting
  205.   ```
  206.  
  207.   **Using `find()` to Check Before Inserting**:
  208.   ```cpp
  209.   auto it = myMap.find(keyToUpdate);
  210.   if (it != myMap.end()) {
  211.   it->second = newValue; // Overwrite
  212.   } else {
  213.   myMap[keyToUpdate] = newValue; // Insert
  214.   }
  215.   ```
  216.  
  217. 6. **Real-World Analogy**:
  218.   - The concept of sorting keys in maps is analogous to looking up words in a dictionary, where words are arranged alphabetically, making them easy to find.
  219.  
  220. If you have any more questions or need further clarification, feel free to ask!
  221. */
  222.  
Success #stdin #stdout 0.01s 5276KB
stdin
8
abc
ghj
jkl
ghj
ghj
abc 
jkl
ghj
stdout
size = 3
date-22
month-5
year-2004

size = 2
date-22
month-5

size = 3
date-22
day-0
month-5

22
5
size = 2
date-22
day-0

size = 1
date-22

size = 1
date-22

size = 0

size = 3
abc-2
ghj-4
jkl-2