【问题标题】:How to rewrite iterator-based for loop into range-based (C++11)如何将基于迭代器的 for 循环重写为基于范围的 (C++11)
【发布时间】:2012-10-08 14:46:07
【问题描述】:

我想重写这个 for 循环(可行)

for (vector<shared_ptr<Node<int>>>::iterator it = n.root.children.begin();
    it != n.root.children.end(); 
    ++it) 
    {cout << (*it)->value<<flush;}

进入基于范围的 for 循环。我尝试的是

for (shared_ptr<Node<int>> child:(n.root).children){
       cout<<(child->value)<<" "<<flush;
    }

但它给了我一个核心转储。根是节点类型

template <typename T>
class Node{
public:
    T value;
    vector<shared_ptr<Node>> children;
};

main.cpp 中的这些行可以正常工作。

cout<<(n.root).value<<flush;
cout<<n.root.children.front()->value<<flush;

我使用 g++ 4.7.2。

【问题讨论】:

    标签: c++ loops for-loop c++11 iterator


    【解决方案1】:

    给你。试试这个。

    for (auto v : n.root.children ) {
        cout << v->value << flush;
    }
    

    【讨论】:

    • 这看起来真不错。不幸的是,结果与上面相同 - coredump。coredump 发生在打印值之后。就像编译器不知道何时结束循环一样。
    • 答案是我们得到的直接翻译。现在的问题是,导致崩溃的原因是什么?发布一个精简但可编译的版本,我们可以解决它。
    • const auto&amp; v 会更好地避免不必要地复制容器值类型。对于std::shared_ptr,这可能是一个互锁的递增和递减。
    • 刚刚注意到在 Qt Creator 中构建和运行 g++ 时可执行文件的行为不同。我会研究这个并在我知道更多时返回。
    • @Jive:他已经在使用共享指针向量,我不是要他开始使用它们。如果它是 std::vector&lt;std::string&gt;,则该点仍然有效 - 如果您使用 auto v,那么您将在每次迭代时创建容器元素的副本。
    猜你喜欢
    • 2015-11-20
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多