Skip to content

Instantly share code, notes, and snippets.

@musteresel
Created June 16, 2015 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save musteresel/8db818354a598b7fee86 to your computer and use it in GitHub Desktop.
Save musteresel/8db818354a598b7fee86 to your computer and use it in GitHub Desktop.
stackoverflow - cities and states
#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