C++ - 制作一个 string+int 集 STL 类型

标签 c++ types stl set multiset

我的问题是:是否可以创建多类型 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/

相关文章:

arrays - Common Lisp 中数组/向量类型的区别?

c++ - 对容器中所有元素的成员函数结果求和的最佳方法是什么?

c++ - 将自定义新处理程序与 Eigen 库一起使用

haskell - 定义幻像类型 - 无法编译示例

c++ - 实现接口(interface)的类的析构函数在引用为接口(interface)时未调用

C# - 通过 if 条件检查值的数据类型

C++ 运算符 << 调用::ostream 而不是 std::ostream

c++ - 我可以以某种方式返回 std::optional 和 const-reference 到我的数据以避免复制它吗?

c++ - 重用字符串流来连续解析来自多个字符串的值

C++ 在 VS 中为 'better' Release模式构建定义