Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sorting by strings in c++

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Try it online!

#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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading