有没有办法在不重载<<运算符的情况下打印出 std::list 的内容?

Is there a way to print out the contents of a std::list without overloading the << operator?

本文关键字:lt std list 打印 运算符 有没有 重载 情况下      更新时间:2023-10-16

我有一些形式:

struct Tree {
    string rule;
    list<Tree*> children;
}

我试图从此内将其打印出来。

for(list<Tree*>::iterator it=(t->children).begin(); it != (t->children).end(); it++) {
    // print out here
}

您随时可以将递归变成迭代。这是一个辅助队列:

std::deque<Tree *> todo;
todo.push_back(t);
while (!todo.empty())
{
    Tree * p = todo.front();
    todo.pop_front();
    std::cout << p->rule << std::endl;
    todo.insert(todo.end(), p->children.begin(), p->children.end());
}

在C 11中,这当然是for循环:

for (std::deque<Tree *> todo { { t } }; !todo.empty(); )
{
    // ...
}