我试图在 C++ 中实现一个后缀树,同时将节点添加到我的向量列表中,它在向树中添加第三个元素后抛出 std::bad_alloc 。我不知道为什么它在第三次之后发生,你能帮我解决这个 bad_alloc 错误吗?
这是我的代码:
suffix_tree.cpp
#include <iostream>
#include <fstream>
#include <cmath>
#include <sstream>
#include <string>
#include <cstring>
#include "node.h"
using namespace std;
Node build_suffix_tree(string text){
Node root = Node();
int n = text.length();
int count;
Node * currentNode = &root;
Node tmpNode;
string suffix;
int suffixLen;
for(int i=0; i<n; i++){
suffix = text.substr(i,n);
suffixLen = suffix.length();
count = 1;
currentNode = &root;
while(count <= suffixLen){
cout << suffix << endl;
int pos = -1;
// bad_alloc occurs here
(*currentNode).addFils(Node(suffix[0], vector<Node>(), i));
cout << currentNode->getFils().size() << endl;
currentNode = ¤tNode[currentNode->getFils().size() - 1];
suffix = suffix.substr(1,suffixLen);
count++;
}
cout << " " << endl;
}
return root;
}
int main(){
string text = "helloeveryone";
Node root = build_suffix_tree(text);
return 0;
}
节点.cpp
#include <string>
#include <vector>
#include "node.h"
using namespace std;
Node::Node(){
c = ' ';
fils = vector<Node>();
pos = -1;
}
Node::Node(char t, vector<Node> l, int p){
c = t;
fils = l;
pos = p;
}
void Node::addFils(Node n){
fils.push_back(n);
}
char Node::getString(void){
return c;
}
vector<Node> Node::getFils(){
return fils;
}
void Node::setFils(vector<Node> l){
fils = l;
}
节点.h
#include <string>
#include <vector>
#ifndef NODE_H
#define NODE_H
class Node
{
public:
char c;
std::vector<Node> fils;
int pos;
Node();
Node(char c, std::vector<Node> fils, int p);
void addFils(Node n);
char getString(void);
std::vector<Node> getFils();
void setFils(std::vector<Node>);
};
#endif // NODE_H
生成文件
CC=g++
CFLAGS= -g
LDFLAGS=
EXEC=suffix_tree
all: $(EXEC)
suffix_tree: suffix_tree.o node.o
$(CC) -o suffix_tree suffix_tree.o node.o $(LDFLAGS)
node.o: node.cpp
$(CC) -o node.o -c node.cpp $(CFLAGS)
suffix_tree.o: suffix_tree.cpp node.h
$(CC) -o suffix_tree.o -c suffix_tree.cpp $(CFLAGS)
clean:
rm -rf *.o
mrproper: clean
rm -rf $(EXEC)
提前致谢。