Created
June 16, 2015 23:31
-
-
Save musteresel/8db818354a598b7fee86 to your computer and use it in GitHub Desktop.
stackoverflow - cities and states
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <map> | |
#include <algorithm> | |
#include <limits> | |
using std::string; | |
using std::vector; | |
using std::map; | |
using std::pair; | |
using std::istream; | |
struct CityEntry { | |
string name; | |
string state; | |
unsigned int inhabitants; | |
}; | |
struct StateInhabitants { | |
unsigned int total; | |
unsigned int lowest; | |
// lowest needs to be set to the maximum value, otherwise you'd need a | |
// special case during the iteration. | |
StateInhabitants() | |
: total(0), lowest(std::numeric_limits<unsigned int>::max()) | |
{} | |
}; | |
vector<CityEntry> read_cities(istream & input) { | |
vector<CityEntry> entries; | |
string name; | |
string state; | |
unsigned int inhabitants; | |
while (input >> name >> state >> inhabitants) { | |
entries.push_back(CityEntry{name, state, inhabitants}); | |
} | |
return entries; | |
} | |
int main(int, char **) { | |
// Input phase | |
vector<CityEntry> cities = read_cities(std::cin); | |
// Transform input to wanted representation | |
map<string, StateInhabitants> state_info; | |
for (CityEntry const & city : cities) { | |
StateInhabitants & inhabitants = state_info[city.state]; | |
inhabitants.total += city.inhabitants; | |
inhabitants.lowest = std::min(inhabitants.lowest, city.inhabitants); | |
} | |
// Print results | |
for (pair<string, StateInhabitants> info : state_info) { | |
std::cout | |
<< info.first | |
<< " " << info.second.lowest | |
<< " " << info.second.total | |
<< std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment