1

I usually work in C, but now I have to work with C++. I have a large file, with a lot of repetition because I can currently not traverse dir_x to dirx_z in a loop.
1. Is there a way to make the elements in this class addressable as if it was, for instance, an array? I give an example of this in the last line.
2. I currently refer to

Node * dir_x;

as being a link, but what is the real name so I can google it?

class Node {
public:
        Node(int x, int y, int z){

                //Will be initialized to point to the next Node (neighbor)
                //So will be holding elements of this same class!
                dir_x = NULL; 
                dir_y = NULL; 
                dir_z = NULL;
        }

        //These are "links", but does anybody know the name to google it?
        Node * dir_x; 
        Node * dir_x; 
        Node * dir_x; 
};

//Code snippet of a function:
//current would be the node to traverse through the collection
Node * current = someNode;
//together with next
Node * next  = NULL;
//Here the next node is actually set
next = current->dir_x;  
//But I would like a generic way like below
//to reduce code duplication by about a third:
next = current->dir[i];
4

2 回答 2

1

欢迎使用 C++。您必须用 C 自己构建的许多东西都是 C++ 标准库的一部分。强烈建议使用这些组件,而不是自己构建。在这种情况下,你应该使用 astd::list而不是浪费所有的时间和脑力来重新发明一个已经完善了一百万次的轮子。

至于你的问题,

//But I would like a generic way like below
//to reduce code duplication by about a third:
next = current->dir[i];

你可以operator[](size_t)在你的Node类上实现一个。我猜它会是这样的:

class Node
{
public:
  Node * mLeft; 
  Node * mRight; 

  Node& operator[] (size_t i) 
  {
    if (!i)
      return *this;
    return (*mRight)[i-1];
  }
};

当然,这只是一个展示。你有很多工作要自己处理,比如范围检查、异常安全等。

于 2013-10-24T13:20:24.157 回答
0

您正在寻找一个链表

    // this would not compile
    Node * dir_x; 
    Node * dir_x; 
    Node * dir_x; 

    // i think you meant
    Node * dir_x; 
    Node * dir_y; 
    Node * dir_z; 

你能做的是

    Node* dir[3]; // now this contains 3 pointers to node elements

你可以随心所欲地使用它

    Node* node_x = node->dir[0];
    Node* node_y = node->dir[1];
    Node* node_z = node->dir[2];

除非node->dir[2]应该给你第二个节点。这也有可能实现。

于 2013-10-24T13:09:32.470 回答