Advertisement
RobertDeMilo

WB2.9 Словари 2

Sep 4th, 2023
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.77 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. void PrintMap(const map <string, int>& m)
  8. {
  9.     cout << "Size: " << m.size() << endl;
  10.  
  11.     for (const auto& item : m) // перестали копировать очередную пару ключ - значение в переменную item c помощью константной ссылки
  12.     {
  13.         cout << item.first << ": " << item.second << endl;
  14.     }
  15. }
  16.  
  17. int main()
  18. {
  19.    ***************************************************************************************
  20.     map <string, int> m = { {"one", 1}, {"two", 2}, {"three", 3} };
  21.     PrintMap(m);
  22.     m.erase("three");
  23.     PrintMap(m);
  24.    ***************************************************************************************
  25.     vector <string> words = { "one", "two", "one" };
  26.     map <string, int> counters;
  27.  
  28.     // Избыточный
  29.     for (const string& word : words)
  30.     {                                   // возвращает сколько раз этот ключ встречается в словаре
  31.         if (counters.count(word) == 0)  // проверка есть ли ключ в словаре
  32.         {
  33.             counters[word] = 1;
  34.         }
  35.         else // иначе такой ключ уже есть в словаре
  36.         {
  37.             ++counters[word];
  38.         }
  39.     }
  40.  ***************************************************************************************
  41.     for (const string& word : words)
  42.     {
  43.         PrintMap(counters);
  44.         ++counters[word];
  45.     }
  46.     PrintMap(counters);
  47.  ***************************************************************************************
  48.     map <string, int> counters;
  49.     counters["a"];
  50.     PrintMap(counters);
  51.  ***************************************************************************************
  52.      // сгруппируем все слова в каком-то наборе по первой букве
  53.     vector <string> words = { "one", "two", "three" };
  54.     map <char, vector <string>> grouped_words; // словарь из символов в набор слов
  55.  
  56.     for (const string& word : words)
  57.     {
  58.         grouped_words[word[0]].push_back(word);
  59.     }
  60.     for (const auto& item : grouped_words)
  61.     {
  62.         cout << item.first << endl;
  63.  
  64.         for (const string& word : item.second)
  65.         {
  66.             cout << word << " ";
  67.         }
  68.  
  69.         cout << endl;
  70.     }
  71.  
  72.     return 0;
  73. }
  74.  
  75. Как только мы обращаемся к какому-то ключу
  76. а) если этот коюч есть, то компилятор возвращает ссылку на него и мы делаем ++
  77. б) если такого ключа еще не было, то компилятор его добавляет со значением 0 (значение по умолчанию)
  78.    
  79. От одного лишь обращения к несуществующему ключу размер словаря может измениться
  80.  
  81.  
Tags: count erase
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement