#include #include #include #include typedef struct CrimeReportRow { std::string address; std::string district; std::string crime; } CrimeReportRow; class CrimeReport { private: std::vector rows; std::vector split(const std::string& line, const std::string delimiter = ",") { std::vector columns; std::string column; int last = 0; int next = 0; while ((next = line.find(delimiter, last)) != std::string::npos) { columns.push_back(line.substr(last, next - last)); last = next + 1; } columns.push_back(line.substr(last)); return columns; } void read_rows(std::string filename) { std::ifstream file(filename); std::string line; int rownumber = 0; if (file.is_open()) { while (std::getline(file, line)) { rownumber++; // skip the first line of the file because it is the heading. if (rownumber == 1) { continue; } std::vector columns = split(line); // skip rows with an unexpected amount of columns. if (columns.size() != 9) { std::cout << "Line " << rownumber << " is not valid!" << std::endl; } CrimeReportRow* row = new CrimeReportRow; row->district = columns[2]; row->address = columns[1]; row->crime = columns[5]; rows.push_back(row); } file.close(); } } public: CrimeReport(std::string filename) { read_rows(filename); } ~CrimeReport() { for (CrimeReportRow* row : rows) { delete row; } rows.clear(); rows.shrink_to_fit(); } int get_number_of_crimes() { return rows.size(); } std::string get_most_frequent_crime() { std::map crimes; for (CrimeReportRow* row : rows) { crimes[row->crime] += 1; } std::pair crime; for (std::map::iterator it = crimes.begin(); it != crimes.end(); it++) { if (it->second > crime.second) { crime = std::make_pair(it->first, it->second); } } return crime.first; } std::string get_most_dangerous_district() { std::map districts; for (CrimeReportRow* row : rows) { districts[row->district] += 1; } std::pair district; for (std::map::iterator it = districts.begin(); it != districts.end(); it++) { if (it->second > district.second) { district = std::make_pair(it->first, it->second); } } return district.first; } std::vector get_list_of_address_with_multiple_crimes() { std::map addresses; for (CrimeReportRow* row : rows) { addresses[row->address] += 1; } std::vector addresses_crimes; for (std::map::iterator it = addresses.begin(); it != addresses.end(); it++) { if (it->second > 1) { addresses_crimes.push_back(it->first); } } return addresses_crimes; } }; int main() { CrimeReport* report = new CrimeReport("input.csv"); std::cout << "Anzahl der Verbrechen: " << report->get_number_of_crimes() << std::endl; std::cout << "Häufigstes Verbrechen: " << report->get_most_frequent_crime() << std::endl; std::cout << "Gefährlichster District: " << report->get_most_dangerous_district() << std::endl; std::cout << "Adresse mit mehr als einem Verbrechen: " << std::endl; for (std::string address : report->get_list_of_address_with_multiple_crimes()) { std::cout << "\t" << address << std::endl; } return 0; }