2013-06-19 29 views
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; 
} 
+0

你可以插入使用INSERT命令来实现。看看这里的例子http://www.cplusplus.com/reference/map/map/insert/ – Pradheep

+0

http://www.cplusplus.com/reference/map/map/operator%5B%5D/ – banuj

回答

2

std::map是一个关联容器,提供Key -> Value关系。在你的情况下,它是std::string -> int。此外

grade_list[ptr] = nr; 

,而不是char阵列,通过strtok我建议使用std::stringboost::algorithm::split,或boost::tokenizer:所以,你应该指定Value同时插入了。


我想看看它时代如何曼尼出现在文本文件中的每个字。

所以,你必须改变mapValue类型std::size_t(因为你din't需要负值):

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

而只是写:

++grade_list[ptr]; 
+0

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

0

你应该大概看看std::map::insert的定义,value_type参数是一个std::pair< std::string, int >,所以你应该写入insert语句如:

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

这将添加一个条目与该键“令牌”和值映射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]++; 
} 
+0

在这里使用'insert'毫无用处。 'operator []'使用键作为键和默认构造的映射值向容器插入新元素,并返回对新构造的映射值的引用。因此,由于内置类型默认使用'0'初始化,所以不需要编写'grade_list [ptr] = 1;'even - 我们可以在两种情况下使用'++ grade_list [ptr];'。 – soon

相关问题