W
William Payne
Hello, I'm working on a program where to user supplies a number of integers
on the command line and then my program displays a list with all the
integers, stating how many times each integer occured, sorted from highest
to lowest.
I thought std::map<int, int> would be a good idea, where the key is an int
supplied on the command line and its value is how many times it occurs. I am
unsure about how to print a sorted list, though. I tried to use
max_element() to see if I can at least get the highest one and work from
there, but it gives me a three page compilation error that I don't intend to
duplicate here. The code I have so far is:
#include <iostream>
#include <map>
#include <sstream>
#include <algorithm>
#include <functional>
using std::map;
using std::cout;
using std::endl;
using std::stringstream;
void count(map<int, int>& the_map, int argc, const char* const argv[]);
int main(int argc, char* argv[])
{
map<int, int> the_map;
count(the_map, argc, argv);
cout << *(std::max_element(the_map.begin(), the_map.end())) << endl;
return 0;
}
void count(map<int, int>& the_map, int argc, const char* const argv[])
{
for(int i = 1; i < argc; ++i)
{
stringstream ss;
ss << argv;
int n = 0;
if(ss >> n)
{
if(the_map.count(n))
{
++the_map[n];
}
else
{
++the_map[n] = 1;
}
}
}
}
If you have any ideas on how to solve this, I'd appreciate it alot if you'd
share them!
/ WP
on the command line and then my program displays a list with all the
integers, stating how many times each integer occured, sorted from highest
to lowest.
I thought std::map<int, int> would be a good idea, where the key is an int
supplied on the command line and its value is how many times it occurs. I am
unsure about how to print a sorted list, though. I tried to use
max_element() to see if I can at least get the highest one and work from
there, but it gives me a three page compilation error that I don't intend to
duplicate here. The code I have so far is:
#include <iostream>
#include <map>
#include <sstream>
#include <algorithm>
#include <functional>
using std::map;
using std::cout;
using std::endl;
using std::stringstream;
void count(map<int, int>& the_map, int argc, const char* const argv[]);
int main(int argc, char* argv[])
{
map<int, int> the_map;
count(the_map, argc, argv);
cout << *(std::max_element(the_map.begin(), the_map.end())) << endl;
return 0;
}
void count(map<int, int>& the_map, int argc, const char* const argv[])
{
for(int i = 1; i < argc; ++i)
{
stringstream ss;
ss << argv;
int n = 0;
if(ss >> n)
{
if(the_map.count(n))
{
++the_map[n];
}
else
{
++the_map[n] = 1;
}
}
}
}
If you have any ideas on how to solve this, I'd appreciate it alot if you'd
share them!
/ WP