遍历 vector<unique_ptr<mytype>>使用 C++11 for() 循环 [英] Iterating through vector&lt;unique_ptr&lt;mytype&gt;&gt; using C++11 for() loops

查看:33
本文介绍了遍历 vector<unique_ptr<mytype>>使用 C++11 for() 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一批代码:

std::vector<std::unique_ptr<AVLTree_GeeksforGeeks>> AVLArray(100000);

/* Let's add some objects in the vector */
AVLTree_GeeksforGeeks *avl = new AVLTree_GeeksforGeeks();
avl->Insert[2]; avl->Insert[5]; AVL->Insert[0];
unique_ptr<AVLTree_GeeksforGeeks> unique_p(avl);
AVLArray[0] = move(unique_p);
/* we do this for a number of other trees, let's say another 9...
...
...
Now the vector has objects up until AVLTree[9] */

/* Let's try iterating through its valid, filled positions */
for(auto i : AVLTree )
{
   cout << "Hey there!\n";    //This loop should print 10 "Hey there"s.
}

Ruh roh.最后一部分的编译错误,在 for() 循环中.

Ruh roh. Compilation error at the last part, in the for() loop.

\DataStructures2013_2014\main.cpp||In function 'int main()':|
\DataStructures2013_2014\main.cpp|158|error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = AVLTree_GeeksforGeeks; _Dp = std::default_delete<AVLTree_GeeksforGeeks>; std::unique_ptr<_Tp, _Dp> = std::unique_ptr<AVLTree_GeeksforGeeks>]'|
e:\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\bits\unique_ptr.h|256|error: declared here|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|

对我做错了什么有任何想法吗?

Any ideas on what I am doing wrong?

推荐答案

循环

for (auto i: AVLTree) { ... }

尝试复制AVLTree.begin()AVLTree.end() 中范围的每个元素.当然,std::unique_ptr是不能复制的:每个指针只有一个std::unique_ptr.它不会真正复制任何东西,而是窃取它.那会很糟糕.

tries to make a copy of each element of the range in AVLTree.begin() and AVLTree.end(). Of course, std::unique_ptr<T> can't be copied: there is only one std::unique_ptr<T> to each pointer. It wouldn't really copy anything but rather steal it. That would be bad.

您想改用引用:

for (auto& i: AVLTree) { ... }

...或者,如果你不修改它们

... or, if you don't modify them

for (auto const& i: AVLTree) { ... }

这篇关于遍历 vector<unique_ptr<mytype>>使用 C++11 for() 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆