-2
我有Java决策树代码要通过C++。 当我尝试构建树时,我不太记得逻辑内部指针。 Java代码:将Java代码转换为C++
public class Node {
Node parent;
Node children[];
List<Instance> instances;
....
};
Node(Node parent, List<Instance> instances) {
this.parent = parent;
children = new Node[Instance.FTSVALUERANGE];
this.instances = instances;
....
}
对于树生成:
public class ID3 {
Node root;
...
public static Node generate(List<Instance> instances) {
Node root = new Node(null, instances);
expand(root, 0);
return root;
}
static void expand(Node node, int depth) {
...
ArrayList<ArrayList<Instance>> ts = new ArrayList<ArrayList<Instance>>();
...
/* Grow the tree recursively */
for (int i = 0; i < Instance.FTSVALUERANGE; i++) {
if (ts.get(i).size() > 0) {
node.children[i] = new Node(node, ts.get(i));
expand(node.children[i], depth + 1);
}
}}}
,在这里我的C++实现;节点:
class Node
{
public:
Node();
Node(Node* parent, std::vector<Instance>& instances);
Node* parent;
Node** children;
std::vector<Instance> instances;
....
};
Node::Node()
{
parent=NULL;
children=NULL;
}
Node::Node(Node* parent, std::vector<Instance>& instances) {
this->parent = parent;
this->children = new Node*[Instance::FTSVALUERANGE];
this->instances = instances;
...
};
对于树生成:
class ID3{
Node* root;
static void expand(Node* node, int depth);
static Node* generate(vector<Instance> instances);
...
};
Node* ID3::generate(vector<Instance> instances) {
Node* root = new Node(NULL, instances);
expand(root, 0);// when use ID3.chi_square_100// there is no prunning,
return root;
}
void ID3::expand(Node* node,int depth){
...
for (int i = 0; i < Instance::FTSVALUERANGE; i++) {
if (ts[i].size() > 0) {
node->children[i] = new Node(node, ts[i]);
expand(node->children[i], depth + 1);
}
}}}
当我尝试运行的东西不工作与儿童。 完整的实现在这里:https://courses.cs.washington.edu/courses/cse446/12wi/ps/hw4/ID3.java
我为我的目的做了一些改变。
在此先感谢。
朱塞佩。
为什么你实现你自己的数据结构?我建议你使用Java和C++中已有的数据结构,或者至少阅读这些实现,以便了解它们的工作原理。当你不了解它们时从头开始编写它们将会浪费大量时间(和错误)如果你的程序中有一个错误,我建议使用你的调试器来找到它。 –
不要使用'NULL',而应使用'nullptr'。不要使用指向指针的指针,并使用'unique_ptr'之类的智能指针,并将'std :: vector'用于动态列表。 –
你好@GuillaumeRacicot,谢谢你的帮助。 “不要使用指向指针的指针,并使用诸如unique_ptr之类的智能指针”是什么意思? –