Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <map>
- #include <vector>
- using namespace std;
- void PrintMap(const map <string, int>& m)
- {
- cout << "Size: " << m.size() << endl;
- for (const auto& item : m) // перестали копировать очередную пару ключ - значение в переменную item c помощью константной ссылки
- {
- cout << item.first << ": " << item.second << endl;
- }
- }
- int main()
- {
- ***************************************************************************************
- map <string, int> m = { {"one", 1}, {"two", 2}, {"three", 3} };
- PrintMap(m);
- m.erase("three");
- PrintMap(m);
- ***************************************************************************************
- vector <string> words = { "one", "two", "one" };
- map <string, int> counters;
- // Избыточный
- for (const string& word : words)
- { // возвращает сколько раз этот ключ встречается в словаре
- if (counters.count(word) == 0) // проверка есть ли ключ в словаре
- {
- counters[word] = 1;
- }
- else // иначе такой ключ уже есть в словаре
- {
- ++counters[word];
- }
- }
- ***************************************************************************************
- for (const string& word : words)
- {
- PrintMap(counters);
- ++counters[word];
- }
- PrintMap(counters);
- ***************************************************************************************
- map <string, int> counters;
- counters["a"];
- PrintMap(counters);
- ***************************************************************************************
- // сгруппируем все слова в каком-то наборе по первой букве
- vector <string> words = { "one", "two", "three" };
- map <char, vector <string>> grouped_words; // словарь из символов в набор слов
- for (const string& word : words)
- {
- grouped_words[word[0]].push_back(word);
- }
- for (const auto& item : grouped_words)
- {
- cout << item.first << endl;
- for (const string& word : item.second)
- {
- cout << word << " ";
- }
- cout << endl;
- }
- return 0;
- }
- Как только мы обращаемся к какому-то ключу
- а) если этот коюч есть, то компилятор возвращает ссылку на него и мы делаем ++
- б) если такого ключа еще не было, то компилятор его добавляет со значением 0 (значение по умолчанию)
- От одного лишь обращения к несуществующему ключу размер словаря может измениться
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement