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

use*_*422 1 c++ stl list

我有一些形式:

struct Tree {
    string rule;
    list<Tree*> children;
}
Run Code Online (Sandbox Code Playgroud)

我正试图从这个for循环中打印出来.

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

Ker*_* SB 5

您总是可以将递归转换为迭代.这是一个辅助队列:

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());
}
Run Code Online (Sandbox Code Playgroud)

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

for (std::deque<Tree *> todo { { t } }; !todo.empty(); )
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)