无序映射它的工作原理
Unordered map how its work
我有一个程序,它计算文件中的单词数并写入文件。一切都是通过有序映射完成的。应该命令它重写映射,并按单词数(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——一个可以有多个键值相同的映射。
建议的解决方案在这里。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- QSqlquery prepare()和bindvalue()不工作
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- C++ 已停止工作静态映射函数
- 使QTConcurrent ::映射与Lambdas一起工作
- C++STL映射键和值工作不正常
- std::以struct为键的映射未按预期工作
- 插入[n X n]矩阵类型的数据,并在运行时对其进行访问.将std::映射工作
- 不确定无序映射是如何工作的
- 无法使无序映射工作
- 从数组映射到整数在C++中无法正常工作
- 使多态性在C++映射中工作,而不会发生内存泄漏
- Boost::在gcc4.6不工作的情况下分配一个大映射的静态初始化
- 调用映射键来调用需要参数的函数-如何工作
- 文件映射是如何工作的
- 正在使std::映射分配器工作
- 无序映射它的工作原理
- openCV重映射与BORDER_REFLECT不工作