Hint
Enter the number of trainers n, and then enter the names of the trainers and their prices and put them into a map where the name of the trainers is the key, and the price is the value.
Create a vector of pairs (model, price) from the map.
Use the function sort from the header <algorithm>.
Make a function that compares two elements so that the larger value comes first, to sort in descending order. Use the name of this function as the third parameter of the function sort.
Print the sorted values of the vector of key–value pairs, where the key is the name and the value is the price of the shoes.
Solution (C++)
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
// Comparison: more expensive trainers first; with the same price – by name (alphabetically)
bool compareOffers(pair<string, int> a, pair<string, int> b)
{
if (a.second != b.second)
return a.second > b.second;
return a.first < b.first;
}
int main()
{
int n;
cout << "Enter the number of trainer models: ";
cin >> n;
map<string, int> trainers; // model -> price
for (int i = 0; i < n; ++i)
{
string model;
int price;
cout << "Enter the trainer model and the price: ";
cin >> model >> price;
trainers[model] = price;
}
// The map is ordered by name; to sort by price we copy it into a vector of pairs
vector<pair<string, int>> offers(trainers.begin(), trainers.end());
sort(offers.begin(), offers.end(), compareOffers);
cout << "\nTrainer names and prices from the most expensive to the cheapest:\n";
for (auto& p : offers)
cout << p.first << " " << p.second << endl;
return 0;
}