I have a vector storing the most frequent words in a file. Initially the values was stored in a map of strings and integers but then I copied the map into the vector I thought it would be easier to sort. Then I realized that the std sort() function sorts the vector by the first key (string in this case). But I want to sort it such that the most used words at the top and the least used at the bottom.
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
int main(){
fstream fs;
fs.open("/Users/brah79/Downloads/skola/c++/codeTest/test.txt");
string word;
map <string, int> list;
while(fs >> word){
if(list.find(word) != list.end()){
list[word]++;
}
else{
list[word] = 1;
}
}
vector <pair <string, int> > vector(list.begin(), list.end());
sort(vector.begin(), vector.end() greater<int>());
for(int i = 0; i < vector.size(); i++){
if(vector[i].second == 1){
cout << vector[i].first << " is repeated " << vector[i].second << " time" << endl;
}
else{
cout << vector[i].first << " is repeated " << vector[i].second << " times" << endl;
}
}
return 0;
}