-1

I have a program that counts the words in a file and writes to the file. Everything is done through the ordered map. It should be ordered to rewrite the map, and sort by the number of words (Int) My 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;
    for (cur = words.begin(); cur != words.end(); cur++)
    {
        out << (*cur).first << ": " << (*cur).second << endl; count += (*cur).second;
    }
    return 0;
}

P.S. I'm sorry I can't work with the ordered map

2 Answers2

0

The most general way to do this is to invert the pairs, push them onto a vector and use std::sort with a comparison function. But multiple keys can have same value. Hence, the sorted list (flipped) is actually a multimap - a map that can have multiple keys with same value.

A proposed solution is here.

Community
  • 1
  • 1
a_pradhan
  • 3,285
  • 1
  • 18
  • 23
0

The elements in std::map is actually std::pair. We store the iterators pointing to pairs in a std::vector, and sort the iterator by providing a 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;
  for (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); 
  for (int i = 0; i < v.size(); ++i) {
    out << v[i]->first << ": " << v[i]->second << endl; count += v[i]->second;
  }
  return 0;
}
Xiaotian Pei
  • 3,210
  • 21
  • 40