[英]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.