我的问题是:是否可以创建多类型 STL 集?如果想从文本文件中计算出现次数,我该怎么做?我只需要使用或...
#include <set>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
set<string, int> danteh;
set<string>::iterator iterator_danteh;
ifstream d1("text.txt");
ofstream d2("output.txt");
string word;
while(!d1.eof())
{
d1 >> word;
danteh.insert(word);
}
cout << endl;
cout << "FINE!";
return 0;
}
最佳答案
使用 std::map
来自 <map>
标题,例如:
std::map< std::string, int > danteh ; // Key is the std::string,
// value is the int
要计算单词数,只需使用以下逻辑:
while ( d1 >> word ) // Extract word from stream
{
danteh[word]++; // Add into map and increment the count
}
对于遍历 map,使用迭代器就像将它用于 set 一样,区别是 first
(键)会给你这个词 second
(值)会给你它的频率。
关于C++ - 制作一个 string+int 集 STL 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24713148/