在c++中映射初始化以实现尝试

maps initialization in c++ for implementing tries

本文关键字:实现 初始化 c++ 映射      更新时间:2023-10-16

我正在尝试在c++中实现尝试。下面是我使用的结构:

typedef struct tries{
    int wordCount;
    int prefixCount;
    map<int,struct tries*> children;
}tries;
initialize方法
void initialise(tries *vertex)
{
    vertex = (tries*)malloc(sizeof(tries*));
    vertex->wordCount = vertex->prefixCount = 0;
    for(char ch='a';ch<='z';ch++)
        vertex->children[ch]=NULL;
}

初始化方法在vertex->children[ch]=NULL;处存在分段故障,故障为:

Program received signal SIGSEGV, Segmentation fault.
0x000000000040139a in std::less<int>::operator() (this=0x604018, 
    __x=@0x21001: <error reading variable>, __y=@0x7fffffffddb8: 97)
    at /usr/include/c++/4.6/bits/stl_function.h:236
236           { return __x < __y; }

怎么了?

如果您正在使用c++,则不应该使用malloc()。此外,如果您需要创建一个tries大小的对象,则不应该分配足够的内存来保存指针(sizeof(tries*))。

使用new操作符:

vertex = new tries();

或者更好,根本不使用new,避免使用原始指针、newdelete.进行手动内存管理,考虑使用智能指针。

同样,在c++中类有构造函数,所以initialise()方法实际上可以用tries的构造函数代替:

struct tries
{
    tries() : wordCount(0), prefixCount(0) 
    {
        // ...
    }
    int wordCount;
    int prefixCount;
    map<int, struct tries*> children;
};