c++ - Unordered map how its work -


i have program counts words in file , writes file. done through ordered map. should ordered rewrite map, , sort number of words (int) program:

#include <iostream> #include <string> #include <map> #include <fstream>  using namespace std;  int main() {      map <string, int> words;     ifstream in;     in.open("in.txt");     string word;     while (in >> word)         words[word]++;     ofstream out;     out.open("out.txt");     int count = 0;     map <string, int>::iterator cur;     out << "words count:" << endl;     (cur = words.begin(); cur != words.end(); cur++)     {         out << (*cur).first << ": " << (*cur).second << endl; count += (*cur).second;     }     return 0; } 

p.s. i'm sorry can't work ordered map

the elements in std::map std::pair. store iterators pointing pairs in std::vector, , sort iterator providing customized compare function.

#include <iostream> #include <string> #include <map> #include <fstream> #include <utility> #include <vector> #include <algorithm>  using namespace std;  typedef map<string,int>::iterator iter; bool compare(iter lhs, iter rhs) {   return lhs->second < rhs->second       || (lhs->second == rhs->second && lhs->first < rhs->first); }  int main() {    map <string, int> words;   ifstream in;   in.open("in.txt");   string word;   while (in >> word)     words[word]++;   ofstream out;   out.open("out.txt");   int count = 0;   map <string, int>::iterator cur;   out << "words count:" << endl;   vector<iter> v;   (cur = words.begin(); cur != words.end(); cur++)   {     // out << (*cur).first << ": " << (*cur).second << endl; count += (*cur).second;     v.push_back(cur);   }   sort(v.begin(), v.end(), compare);    (int = 0; < v.size(); ++i) {     out << v[i]->first << ": " << v[i]->second << endl; count += v[i]->second;   }   return 0; } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -