I was writing a program in C++11 to find top k words from a file. I think priority queues will give the optimal solution so I implemented using that. The code works and compiles. Could anyone please review this and suggest some more C++11/14-ish things to do?I also have some specific questions: Is there way in C++11 or C++14 to avoid using an iterator to find whether an element exists or not in a map?I am talking about the condition: if(it != word_map.end()) {  word_map[word] = ++word_map[word];}How can I avoid using an iterator? Is there a defaultdict in C++ like we have in Python? I suppose here I can just remove it since default initialization will be 0, but what is the general way?I saw a weird behavior for this: while(input_file>>word) {  //....}This loop gives the correct count. But if I do:while(input_file.good()) {   //..}this gives the count with an additional 1 added if the word is present on two different lines.For example:this is a test.this. while giving a count of this as 3.I think I need to write a custom comparator for the priority queue to compare only the second part of the pair. In that case, on what basis is the priority queue operating as of now?/** top k words in a file  */#include <iostream>#include <fstream>#include <map>#include <queue>using namespace std;void getTopKWords(const map<string, int>& word_map, const unsigned int k) {  priority_queue<pair<string, int> > pq;  for(auto item : word_map) {    pq.push(make_pair(item.first, item.second));  }  for(unsigned int i=0;i<k;i++) {    auto item = pq.top();    pq.pop();    cout << item.first <<   <<item.second << endl;  }}void getWordFrequency(const string& filename, const unsigned int& k) {  ifstream input_file;  input_file.open(filename);  if(!input_file.is_open()) {    std::cout<< Error opening file  << std::endl;    return;  }  map<std::string, int> word_map;  std::string word = ;  while(input_file >> word) {    auto it = word_map.find(word);    if(it != word_map.end()) {      word_map[word] = ++word_map[word];    }    else {      word_map[word] = 1;    }  }  input_file.close();  getTopKWords(word_map, k);}int main() {  getWordFrequency(test_file.txt, 5);}
Finding the top k elements from a file
c++;algorithm;c++11