add solution for lab07
This commit is contained in:
48
labs/maps/checkpoint2.cpp
Normal file
48
labs/maps/checkpoint2.cpp
Normal file
@@ -0,0 +1,48 @@
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
if (argc != 2) {
|
||||
cerr << "Usage: " << argv[0] << " inputfile" << endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
ifstream fin(argv[1]);
|
||||
if (!fin) {
|
||||
cerr << "Error opening file " << argv[1] << endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Map to count frequencies; using find/insert instead of operator[].
|
||||
map<int, int> counts;
|
||||
int number;
|
||||
while (fin >> number) {
|
||||
map<int, int>::iterator it = counts.find(number);
|
||||
if (it != counts.end()) {
|
||||
it->second = it->second + 1;
|
||||
} else {
|
||||
counts.insert(pair<int, int>(number, 1));
|
||||
}
|
||||
}
|
||||
|
||||
// Find the maximum frequency.
|
||||
int maxCount = 0;
|
||||
for (map<int, int>::iterator it = counts.begin(); it != counts.end(); ++it) {
|
||||
if (it->second > maxCount) {
|
||||
maxCount = it->second;
|
||||
}
|
||||
}
|
||||
|
||||
// Print all numbers with frequency equal to maxCount.
|
||||
cout << "Modes: ";
|
||||
for (map<int, int>::iterator it = counts.begin(); it != counts.end(); ++it) {
|
||||
if (it->second == maxCount) {
|
||||
cout << it->first << " ";
|
||||
}
|
||||
}
|
||||
cout << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user