【问题标题】:Text Histogram, tokens stored in map文本直方图,存储在地图中的标记
【发布时间】:2013-06-19 12:29:22
【问题描述】:

我正在从文件中读取并使用 strtok 将单词作为标记。我正在尝试将单词存储在地图结构中。我真的不知道如何在地图中插入标记。

到目前为止我的代码:

#include <iostream>
#include <string.h>
#include <fstream>
#include <map>

using namespace std;

//std::map <string, int> grade_list;

int main()
{   
    std::map <string, int> grade_list;

    char text[100];
    int nr=0, i=1;
    char *ptr;

    ifstream myfile("ana.txt");

    if(!myfile.is_open())
        cout << "Could not open file" << endl;
    else
    {
        myfile.get(text, 100);

        ptr = strtok(text, " ,.-?!");

        while(ptr != NULL)
        {
            nr++;

            cout << ptr << endl;
            ptr = strtok(NULL, " ,.-?!");

            grade_list.insert(ptr);

            i++;
        }
    }

    cout << "\nAveti " << nr << " cuvinte." << endl;

    return 0;
}

【问题讨论】:

标签: c++ string text map


【解决方案1】:

std::map 是一个关联容器,提供Key -&gt; Value 关系。在您的情况下,它是std::string -&gt; int。所以,你也应该在插入时指定Value

grade_list[ptr] = nr;

另外,我建议使用strtok 代替char 数组并使用std::stringboost::algorithm::split,或boost::tokenizer


我想查看文件中每个单词在文本中出现的次数。

因此,您必须将Value 类型中的map 更改为std::size_t(因为您不需要负值):

std::map <string, std::size_t> grade_list;

然后写:

++grade_list[ptr];

【讨论】:

  • 我想查看文件中每个单词在文本中出现的次数。
【解决方案2】:

您可能应该查看std::map::insert 定义,value_type 参数是std::pair&lt; std::string, int &gt;,因此您可能应该将插入语句编写为:

grade_list.insert(std::pair< std::string, int >(std::string(ptr), 1));

这将在映射中添加一个条目,其键为“token”,值为 1。

您可能想要的更像是添加一个不存在的条目或增加值:

这可以通过编写类似的东西来实现

if (grade_list.find(ptr) == grade_list.end())
{
    // insert new entry
    grade_list.insert(std::pair< std::string, int >(std::string(ptr), 1)); // can be written as grade_list[ptr] = 1;
}
else
{
    // increment token
    grade_list[ptr] += 1; // can be written as grade_list[ptr]++;
}

【讨论】:

  • 在这里使用insert 是没用的。 operator[] 使用 key 作为键和默认构造的映射值将新元素插入到容器中,并返回对新构造的映射值的引用。因此,由于内置类型默认使用0 初始化,因此甚至不需要编写grade_list[ptr] = 1; - 我们可以在两种情况下都使用++grade_list[ptr];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
相关资源
最近更新 更多