0

我正在从文件中读取并使用 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;
}
4

2 回答 2

2

std::map是一个关联容器,提供Key -> Value关系。在您的情况下,它是std::string -> int. 因此,您也应该Value在插入时指定:

grade_list[ptr] = nr;

另外,我建议使用and , or ,而不是chararray 和 using 。strtokstd::stringboost::algorithm::splitboost::tokenizer


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

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

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

只需写:

++grade_list[ptr];
于 2013-06-19T12:43:42.803 回答
0

您可能应该查看std::map::insert定义,value_type参数是 astd::pair< std::string, int >所以您可能应该将插入语句编写为:

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]++;
}
于 2013-06-19T12:46:04.473 回答