I start with the top node of a tree 5 layers deep, and recursively call getvalue() on each one. Each node is linked to two nodes on the next layer. I’m pretty sure that this is not my issue since I double checked the algorithm on paper. Once I get to layer 3, however, it gives me a segmentation fault. With valgrind, I figured out that it was raised when I tried to print the class variable oper. I have no idea where to go with this, so your help is greatly appreciated.
This is the code:
class Node {
public:
vector<Node> children;
long constval;
char oper;
void setconst();
Node();
void copy(const Node*);
int getvalue();
private:
int mult(int,int);
int div(int,int);
int add(int,int);
int sub(int,int);
};
Node::Node() {
bool c = false;
vector<char> operations;
operations.push_back('m');
operations.push_back('a');
operations.push_back('s');
operations.push_back('d');
operations.push_back('c');
constval = rand();
int randnum = rand() % 5;
cout << randnum << "\n";
oper = operations[randnum];
}
int Node::getvalue() {
cout << oper << '\n';
if (oper == 'm') {
return Node::mult(children[0].getvalue(), children[1].getvalue());
}
else if (oper == 'd') {
return Node::div(children[0].getvalue(), children[1].getvalue());
}
else if (oper == 'a') {
return Node::add(children[0].getvalue(), children[1].getvalue());
}
else if (oper == 's') {
return Node::sub(children[0].getvalue(), children[1].getvalue());
}
else if (oper == 'c') {
return constval;
}
}
EDIT:
Here is my initializing algo:
class Individual {
public:
vector< vector<Node> > nodes;
vector< vector<Node> > getrand();
void replace(vector< vector<Node> >);
void mutate(double);
double run();
Individual();
};
Individual::Individual() {
nodes.resize(5);
nodes[0].resize(1);
int size = 2;
for(int i = 1; i < 5; i++) {
nodes[i].resize(size);
size = size * 2;
}
vector<char> operations;
operations.push_back('a');
operations.push_back('s');
operations.push_back('d');
operations.push_back('m');
nodes[0][0].oper = operations[rand() % 4];
for(int x = 0; x < nodes[4].size(); x++) {
nodes[4][x].setconst();
}
for(int i = 0; i < 4; i++) {
for(int x = 0; x < nodes[i].size(); x++) {
nodes[i][x].children.push_back(nodes[i+1][x*2]);
nodes[i][x].children.push_back(nodes[i+1][x*2+1]);
}
}
}
I have the same opinion as Andrey; that I also don’t like the use of vector as child nodes container. If your data structure is a simple binary tree, why not simply use
as the data members of class Node?
Also, please provide the code for the creation of your tree. It is likely that you have made some mistake there since segmentation fault is very likely due to improper creation of data structure and you may not have realised it.