-3

I have a map containing the following values:

index frequency
65      1
67      5
47      3

In here i want to sort them by frequency in ascending order and print them... Here's my code regarding to this problem:

#include<bits/stdc++.h>
using    namespace    std;
int    main()
{
    string    s;
    while(getline(cin,s))
    {
        map<int,int>m;
        map<int,int>::iterator    it;
        for(int i=0; i<s.size(); i++)
            m[s[i]]++;
        for(it=m.begin(); it!=m.end(); it++)
            cout<<it->first<<" "<<it->second<<endl;
    }
    return    0;
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Shauqi
  • 95
  • 2
  • 7

1 Answers1

4

I encorage you to think a little differently about this problem.

While you currently have a map, i suggest that (atleast for doing this task) to extract the key value pairs.

#include <algorithm>

map<int,int> m;
//fill in
std::vector<std::pair<int,int>> values(m.begin(),m.end());
auto cmp = [](const std::pair<int,int>& l, std::pair<int,int>& r) { return l.second < r.second;};
std::sort(values.begin(),values.end(),cmp);

The above is using c++11 but you can easily make cmp a struct. Complexity is O(nlgn) in time, O(n) in space.

If you have c++11 available, I would also suggest using std::unordered_map instead of std::map, which will have O(1) amoratized insertion and removal rather than O(lg(n)).

IdeaHat
  • 7,641
  • 1
  • 22
  • 53