Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursive member function can't access its own variables
    text
    copied!<p>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 <code>oper</code>. I have no idea where to go with this, so your help is greatly appreciated. This is the code:</p> <pre><code>class Node { public: vector&lt;Node&gt; 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&lt;char&gt; 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 &lt;&lt; randnum &lt;&lt; "\n"; oper = operations[randnum]; } int Node::getvalue() { cout &lt;&lt; oper &lt;&lt; '\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; } } </code></pre> <p>EDIT: Here is my initializing algo:</p> <pre><code>class Individual { public: vector&lt; vector&lt;Node&gt; &gt; nodes; vector&lt; vector&lt;Node&gt; &gt; getrand(); void replace(vector&lt; vector&lt;Node&gt; &gt;); void mutate(double); double run(); Individual(); }; Individual::Individual() { nodes.resize(5); nodes[0].resize(1); int size = 2; for(int i = 1; i &lt; 5; i++) { nodes[i].resize(size); size = size * 2; } vector&lt;char&gt; 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 &lt; nodes[4].size(); x++) { nodes[4][x].setconst(); } for(int i = 0; i &lt; 4; i++) { for(int x = 0; x &lt; 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]); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload