Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将基于迭代器的for循环重写为基于范围的(C+;+;11)_C++_Loops_For Loop_C++11_Iterator - Fatal编程技术网

C++ 如何将基于迭代器的for循环重写为基于范围的(C+;+;11)

C++ 如何将基于迭代器的for循环重写为基于范围的(C+;+;11),c++,loops,for-loop,c++11,iterator,C++,Loops,For Loop,C++11,Iterator,我想重写这个for循环(它可以工作) for(vector::iterator it=n.root.children.begin(); it!=n.root.children.end(); ++(it) {cout value给你。试试这个 for (auto v : n.root.children ) { cout << v->value << flush; } for(自动v:n.root.children){ cout value这看起来真的很不错。

我想重写这个for循环(它可以工作)

for(vector::iterator it=n.root.children.begin(); it!=n.root.children.end(); ++(it) {cout value给你。试试这个

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

cout value这看起来真的很不错。不幸的是,结果与上面的-coredump相同。但是,coredump会在打印完值之后发生。就像编译器不知道何时结束循环一样。答案是我们所给出的内容的直接翻译。现在的问题是,导致崩溃的错误是什么?发布一篇文章n但是可编译版本,我们可以解决它。
const auto&v
会更好地避免不必要的容器值类型复制。对于
std::shared_ptr
,这可能是一个互锁的增量和减量。只是注意到在Qt Creator中构建和运行g++时可执行文件的行为不同。我将保留拱起这个,等我知道更多时再返回。@Jive:他已经在使用共享指针的向量,我不会告诉他开始使用它们。如果是
std::vector
,该点仍然有效-如果使用auto v,则在每次迭代中创建容器元素的副本。
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;
};
cout<<(n.root).value<<flush;
cout<<n.root.children.front()->value<<flush;
for (auto v : n.root.children ) {
    cout << v->value << flush;
}