DimovIvan

C++Advanced-Maps and Sets-Miners(with unordered_map)

Jul 3rd, 2021
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include<iostream>
  2. #include<vector>
  3. #include<unordered_set>
  4. #include<unordered_map>
  5. #include<string>
  6. #include<algorithm>
  7.  
  8.  
  9. std::vector<std::string> readInput() {
  10.     std::vector< std::string > words;
  11.  
  12.     std::string delimiter = "stop";
  13.     std::string currWord;
  14.     std::cin >> currWord;
  15.     while (currWord != delimiter)
  16.     {
  17.         words.push_back(currWord);
  18.         std::cin >> currWord;
  19.     }
  20.  
  21.     return words;
  22. }
  23.  
  24. std::unordered_map<std::string, int> getResources(const std::vector< std::string >& words) {
  25.     std::unordered_map<std::string, int> resources;
  26.     size_t wordsSize = words.size();
  27.     for (size_t i = 0; i < wordsSize - 1; i++)
  28.     {
  29.         if ((i + 1) % 2 != 0)
  30.         {                  
  31.             resources[words[i]] += std::stoi(words[i + 1]);    
  32.         }
  33.     }
  34.     return resources;
  35. }
  36.  
  37. void printSolution(const std::vector<std::string>& wordsInput,
  38.                    const std::unordered_map<std::string, int>& resources)
  39. {
  40.     std::unordered_set<std::string> unicResourses;
  41.  
  42.     const size_t wordsInputSize = wordsInput.size();
  43.     for (size_t i = 0; i < wordsInputSize; i += 2)
  44.     {
  45.         const auto it = resources.find(wordsInput[i]);
  46.         if (unicResourses.find(it->first) == unicResourses.end())
  47.         {
  48.             std::cout << it->first << " -> " << it->second << std::endl;
  49.             unicResourses.insert(it->first);
  50.         }
  51.     }
  52. }
  53.  
  54. int main() {
  55.     const auto wordsInput = readInput();
  56.     const std::unordered_map<std::string, int> resources = getResources(wordsInput);
  57.     printSolution(wordsInput,resources);
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment