Map gerrymanderingRatios(const string &file) { Map countMap; Map> districtVotes; // district : votes Map districtWinner; Map gerryMap; // party : ratio (returned) double totalVotes = 0.0; double districtCounter = 0.0; double ratio = 0.0; ifstream file_in(file); if (file_in) { string line; string districtName; string partyVote; while (file_in >> districtName, getline(file_in, line)) { stringstream ss(line); while (ss >> partyVote) { try { ++countMap[partyVote]; } catch (out_of_range) { countMap[partyVote] = 1; } districtVotes[districtName].push_back(partyVote); ++totalVotes; } string winner; for (auto looker : districtVotes) { sort(districtVotes[districtName].begin(), districtVotes[districtName].end()); int max = 0; for (size_t i = 0; i < districtVotes[districtName].size(); ++i) { int counter = count(districtVotes[districtName].begin(), districtVotes[districtName].end(), districtVotes[districtName][i]); if (counter > max) { max = counter; winner = districtVotes[districtName][i]; } } } districtWinner[districtName] = winner; ++districtCounter; } } file_in.close(); Map::iterator voteCounter = countMap.begin(); // countMap for (; voteCounter != countMap.end(); ++voteCounter) { Map::iterator partyCounter = districtWinner.begin(); // districtWinner int districtsWon = 0; for (; partyCounter != districtWinner.end(); ++partyCounter) { if (*voteCounter == districtWinner.get(*partyCounter)) ++districtsWon; } double percentOfVotes = countMap.get(*voteCounter) / totalVotes; // total votes / # of party votes double percentDistrictsWon = districtsWon / districtCounter; // districts won by party / # of districts ratio = percentDistrictsWon / percentOfVotes; gerryMap[*voteCounter] = ratio; } return gerryMap; }