Advertisement
Guest User

Untitled

a guest
Mar 1st, 2021
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <string>
  5. #include <algorithm>
  6.  
  7. struct Salary
  8. {
  9.     double Value;
  10. };
  11.  
  12. using Name = std::string;
  13. // You may want to have this as a shared_ptr.
  14. using NameSalarySlotMap = std::map<Name, Salary*>;
  15. using Salaries = std::vector<Salary*>;
  16.  
  17. NameSalarySlotMap nameSalaryMap;
  18. Salaries salaries;
  19.  
  20. void add_new_name_and_salary(const char *name, double value)
  21. {
  22.     Salary *salary = new Salary;
  23.     salary->Value = value;
  24.  
  25.     // Insert the pair inside the map so we can get a person's salary without iterating the vector.
  26.     // TODO: make sure name is unique and not already present inside the map.
  27.     nameSalaryMap.insert({name, salary});
  28.  
  29.     // Keep the vector sorted.
  30.     // TODO: it will probably be faster to insert salary directly at the right position instead of sorting the array
  31.     // each time.
  32.     salaries.push_back(salary);
  33.     std::sort(salaries.begin(), salaries.end(), std::greater<>());
  34. }
  35.  
  36. void change_salary_for_name(const char *name, double delta)
  37. {
  38.     nameSalaryMap[name]->Value += delta;
  39.     std::sort(salaries.begin(), salaries.end(), std::greater<>());
  40. }
  41.  
  42. int main()
  43. {
  44.     add_new_name_and_salary("Foo", 10);
  45.     add_new_name_and_salary("Bar", 20);
  46.     add_new_name_and_salary("Baz", 15);
  47.  
  48.     // Will print: 20 15 10
  49.     for (const auto &salary : salaries)
  50.     {
  51.         std::cout << salary->Value << " ";
  52.     }
  53.     std::cout << "\n";
  54.  
  55.     change_salary_for_name("Baz", 30);
  56.    
  57.     // Will print: 45 20 10
  58.     for (const auto &salary : salaries)
  59.     {
  60.         std::cout << salary->Value << " ";
  61.     }
  62.     std::cout << "\n";
  63.  
  64.     return 0;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement