具有多个指针初始化程序的C ++ for循环

时间:2019-05-09 14:09:05

标签: c++

在下面的for循环中:

struct Block
{
    Block(int d) : data(d), next(nullptr) {}

    int data;
    Block* next;
};

Block* aList = new Block(1);
Block* bList = new Block(2);

for (Block* a = aList, *b = bList; a != nullptr; a = a->next, b = b->next)
    if (aList->data != bList->data)
        cout << "Difference found.\n";

我不喜欢将*放在b之前,但是当然需要将Block与Block *区分开。还有另一种方法吗? for ((Block*) a, b...不适合。

6 个答案:

答案 0 :(得分:5)

您可以这样做:

for (auto a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
    if (aList->data != bList->data)
        cout << "Difference found.\n";

答案 1 :(得分:2)

如果您不想重复*,则可以使用using并创建一个别名BlockPtr,而不是Block*

int main() {
  using BlockPtr = Block*;

  BlockPtr aList = new Block(1);
  BlockPtr bList = new Block(2);

  for (BlockPtr a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
    if (aList->data != bList->data)
      cout << "Difference found.\n";
}

或在auto上中继:

int main() {

  auto aList = new Block(1);
  auto bList = new Block(2);

  for (auto a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
    if (aList->data != bList->data)
      cout << "Difference found.\n";
}

答案 2 :(得分:1)

是的,只需使用:

Block* a = aList, *b = bList

编辑:

选项1-使用Boost

#include <boost/typeof/typeof.hpp>
/*
    ...
*/
for (BOOST_TYPEOF_KEYWORD(Block*) a = aList, b = bList;...)

另一个选择是创建所需类型的单个变量,并使用该类型来初始化其他变量(类似于auto):

选项2

Block* aList = new Block(1);
Block* bList = new Block(2);

for (decltype(aList) a = aList, b = bList; ...) ...

选项3-使用Boost

#include <boost/typeof/typeof.hpp>
/*
    Like the first option
*/
for (BOOST_TYPEOF(aList) a = aList, b = bList;...) ...
// ...

答案 3 :(得分:1)

声明指针时,*属于名称,而不是类型。这意味着您可以使b这样的指针

for (Block *a = aList, *b = bList; a != nullptr; a = a->next, b = b->next)

答案 4 :(得分:1)

您试图在一个表达式中声明两个指针。

Block* a = aList, b = bList;

它恰好是for循环的一部分,但是就像

int * a, * b;

是两个int指针,可以使用

Block* a = aList, * b = bList;

在您的for循环中。

答案 5 :(得分:0)

仅定义type alias怎么样?

using BlockPtr = Block*;

for (BlockPtr a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
    if (aList->data != bList->data)
        cout << "Difference found.\n";