【问题标题】:Iterating through vector<unique_ptr<mytype>> using C++11 for() loops使用 C++11 for() 循环遍历 vector<unique_ptr<mytype>>
【发布时间】:2013-12-16 01:24:46
【问题描述】:

我有以下一批代码:

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()循环中。

\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) ===|

关于我做错了什么有什么想法吗?

【问题讨论】:

    标签: c++ c++11 vector unique-ptr


    【解决方案1】:

    循环

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

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

    您想改用引用:

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

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

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

    【讨论】:

    • 非常感谢您,先生。一个问题,它看起来像这样的循环遍历整个 AVLArray,即使它的位置只有 10 个被分配。任何仅通过非空循环的内置方式?
    • @DimitrisSfounis:显而易见的方法是将更多元素放入数组中,然后应该有!只需reserve() 足够的空间并添加元素,例如,使用push_back()emplace_back()
    • @Dietmar_Kühl 不幸的是,我必须分配数百万个空格。我想自己使用 push_back,但我不能。我想 if(i) 会起作用,但是由于我的向量大约是半满的,所以我只会“烧掉”大约 500.000 个循环。该死的。
    • for(auto&amp;&amp; i : AVLTree) {// do something}怎么样
    • @shuva:使用转发引用也可以。它适用于所有三种情况(非const 范围、const 范围和返回临时对象的范围,尽管后者应该相当少见)。不过,资格将取决于提供的范围而不是预期用途。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2013-02-20
    • 2011-03-18
    相关资源
    最近更新 更多