Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <algorithm>
- using namespace std;
- int total_cities = 0,
- total_regions = 0;
- struct City {
- string name;
- string region;
- int population;
- } cities[103];
- struct Region {
- string name = "";
- int population = 0;
- int smallest_population = 600000; // 600 000 is highest possible value
- } regions[10];
- void read_data();
- void write_data();
- void add_region_city(int index, int population);
- bool region_compare(Region region1, Region region2);
- int main()
- {
- read_data();
- for (int i = 0; i < total_cities; i++) {
- for (int r = 0; r < 10; r++) {
- // if region name is already in list, skip loop
- if (regions[r].name == cities[i].region) {
- add_region_city(r, cities[i].population);
- break;
- }
- // if region's name isn't set and current index is free, set region name
- if (regions[r].name == "") {
- total_regions++;
- regions[r].name = cities[i].region;
- add_region_city(r, cities[i].population);
- break;
- }
- }
- }
- sort(regions, regions + total_regions, region_compare);
- write_data();
- return 0;
- }
- /**
- * Reads data from input file
- */
- void read_data() {
- ifstream datafile;
- datafile.open("U2.txt");
- if (datafile.is_open()) {
- datafile >> total_cities;
- for (int i = 0; i < total_cities; i++) {
- datafile >> cities[i].name >> cities[i].region >> cities[i].population;
- }
- }
- }
- /**
- * Writes results to output file
- */
- void write_data() {
- ofstream outputfile;
- outputfile.open("U2Rez.txt");
- if (outputfile.is_open()) {
- outputfile << total_regions << endl;
- for (int i = 0; i < total_regions; i++) {
- outputfile << regions[i].name << " ";
- outputfile << regions[i].smallest_population << " ";
- outputfile << regions[i].population << " ";
- outputfile << endl;
- }
- }
- }
- /**
- * Adds city population to region population, and checks,
- * if it's smallest city population
- *
- * int index - array index of region
- * int population - population of city
- */
- void add_region_city(int index, int population) {
- regions[index].population += population;
- if (regions[index].smallest_population > population)
- regions[index].smallest_population = population;
- }
- /**
- * Comparing function for sorting regions by smallest city
- * and alphabet (sort function's third argument)
- */
- bool region_compare(Region region1, Region region2) {
- if (region1.smallest_population == region2.smallest_population) {
- return region1.name < region2.name;
- } else {
- return region1.smallest_population < region2.smallest_population;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement