There is a txt file that contains the following data:
- the name of a city
- a temperature in the city, measured in celsius
for example
London 3
Washington 11
Budapest 3
London 5
Budapest 30
Washington 11
London 15
Budapest 7
How can I calculate each city’s average temperature. Can I somehow sort it and create a structure by the city names, or what is the best solution for this issue?
>Solution :
std::map does everything for you – it aggregates by same key (city name) and also sorts all keys (city names), because std::map gurantees to keep all keys in sorted order.
In map I keep city name as key and pair of temperature sum and count as value. Finally average temperature can be computed as sum divided by count.
#include <fstream>
#include <map>
#include <iomanip>
#include <iostream>
int main() {
{
std::ofstream f("test.txt");
f << std::string(
"London 3 \n Washington 11 \n Budapest 3 \n London 5 \n"
"Budapest 30 \n Washington 11 \n London 15 \n Budapest 7 \n");
}
{
std::ifstream f("test.txt");
std::map<std::string, std::pair<int, int>> temps;
std::string name;
int temp = 0;
while (f >> name >> temp) {
temps[name].first += temp;
++temps[name].second;
}
for (auto const & [name, avg]: temps)
std::cout << name << ": " << std::fixed << std::setprecision(2)
<< 1.0 * avg.first / avg.second << std::endl;
}
}
Output:
Budapest: 13.33
London: 7.67
Washington: 11.00