将Java代码翻译成C++

Translate Java code to C++

本文关键字:C++ 翻译 代码 Java      更新时间:2023-10-16

我有Java决策树代码要用C++传递。当我试图构建树时,我不太记得逻辑内部指针。Java代码:

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
为了我的目的,我做了一些改变
提前谢谢
朱塞佩。

感谢Guillaume Racicot的建议
这是代码:
在Node.cpp中:

class Node
{
public:
    Node();
    Node(Node* parent, std::vector<Instance>& instances);
    Node* parent;
    std::vector<Node*> children;
    ....
};
Node::Node(Node* parent, std::vector<Instance>& instances) {
    this->parent = parent;
    this->children= std::vector<Node*>(Instance::FTSVALUERANGE);
    ...
}