在c++中映射初始化以实现尝试
maps initialization in c++ for implementing tries
我正在尝试在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
,避免使用原始指针、new
和delete.
进行手动内存管理,考虑使用智能指针。
同样,在c++中类有构造函数,所以initialise()
方法实际上可以用tries
的构造函数代替:
struct tries
{
tries() : wordCount(0), prefixCount(0)
{
// ...
}
int wordCount;
int prefixCount;
map<int, struct tries*> children;
};
相关文章:
- 如何实现使用 gcc-4.4 编译的大向量初始化?
- 在声明或实现中延迟初始化C++单一实例
- 为什么make_tuple的实现不会通过大括号初始化返回?
- 生产者消费者实现中的条件变量应如何初始化
- 如何在C++中实现初始化终结器
- 在某些情况下,如何理解允许实现将非局部变量的动态初始化视为静态初始化
- 如何实现便捷的初始化?
- 逗号分隔的初始化(如Eigen中的初始化)如何可能在C++中实现
- 我是否必须在函数的声明和实现中编写初始化列表
- c2797 成员初始值设定项列表或非静态数据成员初始值设定项中的列表初始化未实现
- C++编译器在 main 之后实现动态初始化
- 使用纯虚拟函数的实现初始化
- 抱歉,未实现:c++ 11中的非静态数据成员初始化器
- 尝试为特征矩阵实现一种初始化列表语法
- 如何初始化实现文件中的静态常量集<string>?
- 在c++中映射初始化以实现尝试
- 定义了静态初始化实现的顺序
- 如何实现RAII +延迟初始化
- 在C++中实现全局变量和静态成员变量的动态初始化
- 这两个矢量初始化是否实现相同的结果