1
我想改寫這個for循環(工作)如何重寫迭代器爲基礎的循環成基於範圍(C++ 11)
for (vector<shared_ptr<Node<int>>>::iterator it = n.root.children.begin();
it != n.root.children.end();
++it)
{cout << (*it)->value<<flush;}
成範圍爲基礎的循環。我試過的是
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。
這看起來非常好。不幸的是,結果與上面一樣 - coredump。然而,在數據打印完成後,coredump發生了。就好像編譯器不知道何時結束循環一樣。 – Slazer
答案是我們所得到的直接翻譯。現在的問題是,什麼是錯誤導致崩潰?發佈精簡版但可以編譯的版本,我們可以解決它。 –
'const auto&v'會更好地避免不必要的容器值類型的複製。對於'std :: shared_ptr',這可能是一個互鎖的增量和減量。 –