c++ - C++中无序集的大小是否有限制

标签 c++ c++11 unordered-set

我正在解析一个带有单词和标签(看起来像单词/标签)的文本文件。我试图在我的文件中找到唯一标签的数量,并使用 C++ 中的无序集来插入标签。然而,我似乎随机得到这个异常:“EXC_I386_GPFLT”在插入(在未确定的插入次数之后)到我的无序集合中。我不认为我内存不足,因为 Xcode 说我只使用 ~300 - 400 KB。

这是我的主要功能:

#include <iostream>
#include "ParseTrain.h"

int main(int argc, const char * argv[])
{
    ParseTrain p("~/Desktop/treebank.5290.train");
    std::cout<<"The Number of Tags is: "<<p.getSizeOfTag()<<std::endl;
    return 0;
}

这是我的 ParseTrain.cpp:

#include "ParseTrain.h"
#include <fstream>
#include <string>
#include <iostream>


ParseTrain::ParseTrain(std::string fName){
    std::ifstream file(fName);
    std::string word;

    if(!file)
        return;

    //read file by word
    while(file >> word ){
        char * cWord = new char (word.size()+1);
        std::strcpy(cWord,word.c_str());

        char *p = std::strtok(cWord, "/");
        std::string key = p;
        p = strtok(NULL, " ");
        std::string value = p;
        std::cout<<value<<std::endl;
        _tag.insert(value);//getting exception thrown after undeterminable number of inserts at this line
        delete [] cWord;
        cWord = NULL;
    }
}

这是我的 ParseTrain.h:

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <unordered_set>

class ParseTrain{
private:

    //map to relate the work and part of speech tag
    std::vector <std::map<std::string, std::string>> _sentence;
    std::unordered_set<std::string> _tag;
public:

    //constructor to parse file
    //takes in path to file to parse
    ParseTrain(std::string fName);

    inline size_t getSizeOfTag(){
        return _tag.size();
    }
};

最后这是我试图解析并获取标签的文本文件的一小部分:

Pierre/NP Vinken/NP ,/, 61/CD years/NNS old/JJ ,/, will/MD join/VB the/DT board/NN as/IN a/DT nonexecutive/JJ director/NN Nov./NP 29/CD ./. 
Mr./NP Vinken/NP is/VBZ chairman/NN of/IN Elsevier/NP N.V./NP ,/, the/DT Dutch/NP publishing/VBG group/NN ./. 

我真的不明白为什么插入时会抛出异常。我唯一能想到的是无序集的大小可能有限制,但考虑到我使用的内存如此之少,这似乎很奇怪。任何帮助将不胜感激。

最佳答案

这个:

char * cWord = new char (word.size()+1);

应该是这样的:

char * cWord = new char [word.size()+1];

注意括号。

第一个分配一个字节,并将其初始化为word.size()+1。第二个分配 word.size()+1 字节。

关于c++ - C++中无序集的大小是否有限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22061441/

相关文章:

c++ - 为类型特征排序多个 std::void_t 部分特化的可靠方法

c++ - 从 Codechef March Long 竞赛中获得 ANUGCD 中的 WA

c++ - 如何从返回有符号整数的函数中返回错误

c++ - 用于创建业余操作系统的最受尊敬的语言和免费编译器?

c++ - 如何让输出流稍后执行某些操作?

c++ - 对的无序 multimap

c++ - std::string_view 和 std::string in std::unordered_set

c++ - 在 C++ 中为 unordered_set 声明散列函数?

c++ - C++中成员函数的const&,&和&&&说明符

c++ - 我们如何更改此函数以支持多个参数?