簡體   English   中英

在QVector上使用std :: find <std::unique_ptr<Type> &gt;

[英]Use std::find on QVector<std::unique_ptr<Type>>

編碼

以下是我遇到問題的類的縮小實現:

class Dummy{
public:
    Dummy();
    ~Dummy();
    void addItem(std::unique_ptr<Type>&& item);
private:
    QVector<std::unique_ptr<Type>> collection;
}

上面的代碼片段中的Type是另一個支持move語義的類。 這是addItem成員的實現:

void Dummy::addItem(std::unique_ptr<Type>&& item){
    if((std::find(collection.begin(), collection.end(), item) == colection.end()){
        collection.push_back(std::move(item));
    }
}

我使用Dummy類,如下所示:

Dummy myDummy;
std::unique_ptr<Type> item(new Type());
myDummy.addItem(sdt::move(item));

問題

編譯器報告以下內容:

required from 'QVector<T>::iterator QVector<T>::begin()'
required from here
use of deleted function 'std::unique_ptr<_Tp,_Dp>::unique_ptr(const std::unique_ptr<_Tp,_Dp>&)'

這是否意味着我無法在QVector<std::unique_ptr<Type>>使用提供的迭代器進行迭代,因此無法使用算法標頭提供的std::find
我可以為for(auto const& other : collection)使用range-base,並為Type實現相等運算符,以便從std::find獲得行為。
我無法理解該示例在哪里出錯。

問題在於,當您執行以下操作時, QVector復制(復制構造)其元素:

  • 使用push_back()函數添加它們。
  • 獲取非常量迭代器到容器的末端。

為了避免第二個,您必須使用相當常量的迭代器,即QVector::constBegin()QVector::constEnd() ,即

if (std::find(collection.constBegin(), collection.constEnd(), item) == collection.constEnd()) {...}

為了避免在添加時復制... hm,我建議改用std::vector

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM