I am sorting the elements in an array according to their frequency of occurrence in decreasing order and if two elements have same frequency then they are sorted in increasing order. I have used std::map
to count the frequency and then copy the elements from std::map
to std::vector<std::pair<K, V>>
.
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
struct greater
{
template<class T>
bool operator()(T const &a, T const &b) const { return a.second > b.second; }
};
template<class T>
void sortByFreq(std::vector<T>& v)
{
std::map<T, T> count;
for (int i : v){
count[i]++;
}
std::vector<std::pair<T, T>> mapcopy;
for(auto itr = count.begin(); itr != count.end(); itr++)
{
mapcopy.push_back(*itr);
}
std::sort(mapcopy.begin(), mapcopy.end(), greater());
std::cout << "Elements sorted according to Frequency \n";
auto itr = mapcopy.begin();
while(itr != mapcopy.end())
{
for(int i = 0; i < itr->second; i++)
{
std::cout << itr->first <<" ";
}
itr++;
}
}
int main()
{
std::vector<int> vec = {2, 3, 2, 4, 5, 12, 12, 3, 4, 3};
sortByFreq(vec);
std::vector<char> c ={ 'e', 't', 'r', 'e', 't', 't', 'f'};
sortByFreq(c);
return 0;
}
The Output is
3 3 3 2 2 4 4 12 12 5
t t t e e f r
Review this code and help me to improve it.