【问题标题】:Using STL Map & Set for reocurring words使用 STL Map & Set 重复出现的单词
【发布时间】:2016-09-27 16:31:20
【问题描述】:

我目前正在开发一个程序,该程序将接收文本文件并将每个单词组织成它自己的值以及它出现的次数。我一直在玩这个想法很长一段时间,并且无法超越基本实现。我对使用 MAP 和 SET 非常陌生,我知道 SET 只会保存每个单词的一次出现,并且 MAP 可以使用单词本身作为键,它的数据类型可以是它重复的次数。但是,要做到这一点,我很失落。我的代码不完整,我被卡住了,我试图做的是找出一种方法将每个单词存储在 SET 中,并立即将单词映射到一个映射的原始值,但是,如果一个单词重复,那么集合会抓住它并将 MAP KEY - VALUE 对增加一。

例子:

#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;

int main()
{
    map<string, int> testMap;
    vector<string> text;
    set<string> words;
    int datVal = 1;

    text.push_back("Hi");
    text.push_back("Hi");
    text.push_back("Bye");
    text.push_back("test");
    text.push_back("ice");
    text.push_back("pie");
    text.push_back("pie");
    text.push_back("cheese");
    text.push_back("wampum");

    for(int x = 0; x < text.size(); x++)
    {
    words.insert(text[x]);
    if(
    testMap.insert(make_pair(text[x], datVal)).second;

    }

如果有人可以帮助我,我将不胜感激!我什至不明白如何检查设置并增加链接到地图的值,我还有很多东西要学。感谢您的宝贵时间!

【问题讨论】:

    标签: c++ dictionary iterator set


    【解决方案1】:

    假设我们有一个包含您的单词数据的std::vector&lt;std::string&gt;。如果我们想在这个向量中创建一个单词的直方图,那么使用单个std::map&lt;std::string, unsigned int&gt; 是简单而有效的,方法是使用std::map::operator[] 探测映射实例,该实例访问与传递给此方法的键对应的值的引用,或者如果数据尚未包含在地图中,则插入数据:

    int main() {
        std::vector<std::string> words; // populated somewhere
        std::map<std::string, unsigned int> word_histogram; // store word with associated count
        for (const auto& word : words) ++word_histogram[word]; // find word and increment count
    }
    

    这会生成包含在std::vector 单词中的单词的直方图。请注意,如果您不关心word_histogram 中项目的顺序,请改用std::unordered_map&lt;std::string, unsigned int&gt;,因为std::unordered_map::operator[] 的平均案例复杂度是恒定的,而std::map::operator[] 的容器大小是对数。

    对于您在问题开头提到的要求,无需使用额外的std::set,这可以使用上面的代码简单地实现。

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      相关资源
      最近更新 更多