Does anyone know how to do this?
I attached a program that collects all the command line arguments into a map container noting how many times each command line argument occurs. Now I want to sort this map of information by loading a vector with iterators that point to each map element and sort the iterators. I'm just wondering, what is the best way to do this. My method works but I'm wondering is it the proper way to do it?.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iterator>
#include <algorithm>
struct mys
{
unsigned long a;
};
std::ostream& operator <<(std::ostream & out, const struct mys & m)
{
return out << m.a;
}
std::ostream& operator <<(std::ostream & out, const std::pair<const std::string, struct mys> & p)
{
return out << p.first << " " << p.second;
}
std::ostream& operator <<(std::ostream & out, const std::map<std::string, struct mys>::const_iterator & i)
{
return out << *i;
}
bool compare_iterator(const std::map<std::string, struct mys>::const_iterator & a, const std::map<std::string, struct mys>::const_iterator & b)
{
return a->second.a > b->second.a || ( a->second.a == b->second.a && a->first > b->first );
}
int main(int argc, char** argv)
{
std::map<std::string, struct mys> the_words;
std::vector<std::map<std::string, struct mys>::const_iterator > the_vec;
for (std::map<std::string, unsigned long>::size_type i = 1; i < argc; ++i)
the_words[argv[i]].a++;
std::map<std::string, struct mys>::const_iterator begin = the_words.begin();
std::map<std::string, struct mys>::const_iterator end = the_words.end();
while ( begin != end )
{
the_vec.push_back(begin);
++begin;
}
sort(the_vec.begin(), the_vec.end(), compare_iterator);
copy(the_vec.begin(), the_vec.end(), std::ostream_iterator<std::map<std::string, struct mys>::const_iterator >(std::cout, "\n"));
return 0;
}