无序映射它的工作原理

Unordered map how its work

本文关键字:工作 映射 无序      更新时间:2023-10-16

我有一个程序,它计算文件中的单词数并写入文件。一切都是通过有序映射完成的。应该命令它重写映射,并按单词数(Int)排序。程序:

#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;
}

注:对不起,我不能使用有序地图

std::map中的元素实际上是std::pair。我们将指向对的iterator存储在std::vector中,并通过提供自定义比较函数对迭代器进行排序。

#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;
}

最一般的方法是将这对对反转,将它们压入一个向量,并使用std::sort和比较函数。但是多个键可以有相同的值。因此,排序列表(翻转)实际上是一个multimap——一个可以有多个键值相同的映射。

建议的解决方案在这里。