【问题标题】:C++: How to iterate through a double pointer pointing to an array of pointersC ++:如何遍历指向指针数组的双指针
【发布时间】:2021-05-29 09:34:52
【问题描述】:

在下面的代码中,我将遍历一个指向 TreeNode 对象的指针数组的指针。下面是我遍历数组的代码:

TreeNode* childListPointer = *currNode->children;


for (TreeNode* currChild = childListPointer; currChild != NULL; currChild = ++childListPointer) {
    std::cout << "Iteration" << endl;
}

下面是我的 TreeNode 结构的代码:

typedef struct TreeNode { 
   int key;
   int val;
   bool flag;
   int num_children;
   TreeNode **children;
} TreeNode; 

但是,即使数组的长度很小(例如 4 或 5),我的代码也会一直陷入无限循环。

注意:自动评分系统不允许我修改 TreeNode 结构

【问题讨论】:

  • currChild != NULL 这将永远是true

标签: c++ arrays pointers memory-management


【解决方案1】:

您的数组是一个大小和计数。

int num_children;
TreeNode **children;

基于此,您可以为for(:) 循环制作一个简单的范围适配器:

template<class It>
struct range {
  It s, f;
  It begin() const { return s; }
  It end() const { return f; }
  range(It b, It e):s(b),f(e) {}
  range(It b, std::ptrdiff_t count):range(b, b+count) {}
};

现在,只是:

for(TreeNode* child : range{ currNode->children, currNode->num_children })
{
  std::cout << "Iteration" << endl;
}

之前,您需要一个make_range

template<class It>
range<It> make_range( It b, It e ) { return {b,e}; }
template<class It>
range<It> make_range( It b, std::ptrdiff_t c ) { return {b,c}; }

for(TreeNode* child : make_range( currNode->children, currNode->num_children ))
{
  std::cout << "Iteration" << endl;
}

因为在中添加了“演绎指南”。

你就完成了。您现在可以在不进行任何指针运算和混淆的情况下遍历子代。

...

如果你被困在 你可以这样做:

for (int i = 0; i < currNode->num_children; ++i)
{
  TreeNode* child = currNode->children[i];
  std::cout << "Iteration" << endl;
}

TreeNode** it = currNode->children;
TreeNode** end = it+currNode->num_children;
for (; it != end; ++it)
{
  TreeNode* child = *it;
  std::cout << "Iteration" << endl;
}

这几乎正是 range 版本编译成的内容。

【讨论】:

  • 感谢您的快速回复:D。有没有办法在不修改 TreeNode 结构的情况下遍历双指针数组?
  • @AdamLee 该类型和函数不属于TreeNode。它们只是您编写和使用的实用程序功能。 TreeNode 完全没有改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-12
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
相关资源
最近更新 更多