-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfreqSort.cpp
More file actions
51 lines (44 loc) · 1.36 KB
/
Copy pathfreqSort.cpp
File metadata and controls
51 lines (44 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
Sort the characters in a string by their frequency. For example, after
sorting, the string "araprt" should be sorted as "aarrpt" or "rraatp", etc.
*/
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility> // std::pair
#include <vector>
#include <algorithm> // std::sort
using std::cout;
using std::string;
using std::unordered_map;
using std::pair;
using std::vector;
// sort the vector in ascending order of its pairs' second value, unless
// they are equal, in which sort by that pair's first value.
bool sortAsc(const pair<char,int> &a, const pair<char,int> &b) {
if (a.second != b.second)
return b.second < a.second;
return a.first < b.first;
}
int main()
{
string inStr = "araprt";
// map each unique char to its occurance frequency
unordered_map<char,int> umap;
for (auto& e:inStr)
if (umap.find(e) == umap.end())
umap.insert(pair(e,1));
else
umap[e] += 1;
// sort the key:value map by value. Do this by copying the map into a vector
// of key-value pairs and sort that.
vector<pair<char,int>> vec;
std::copy(umap.begin(), umap.end(), std::back_inserter(vec));
std::sort(vec.begin(), vec.end(), sortAsc);
// print the sorted vector
for (auto& e:vec) {
for (int i=0; i<e.second; i++)
cout << e.first;
}
cout << "\n";
}