2017-09-15 83 views
-1

如何删除对象形式的QList删除一个项目从QList作抛出错误

QList<CascadeJobInfo> m_InternJobInfoList; 
foreach (CascadeJobInfo jobInfo, m_InternJobInfoList) 
{ 

    m_InternJobInfoList.removeOne(jobInfo); 
} 

它抛出错误 C:\ Qt的\ Qt5.7.0 \ 5.7 \ mingw53_32 \包括\ QtCore \ qlist.h:972 :错误:不对应的 '运营商=='(操作数类型是 'CascadeJobInfo' 和 '常量CascadeJobInfo') 如果(N-> T()== T) ^

+0

一旦你调用removeOne,列表不保持和以前一样。因为某些元素已经被带走,所以Foreach可能会超出范围。 –

+1

@PhạmAnhTuấn'foreach'获取列表的副本,因此如果效率低下,此代码是安全的。 –

+0

:(所以它是安全的使用迭代器而不是foreach – Sijith

回答

2

您需要实现operator==类型CascadeJobInfo

class CascadeJobInfo 
{ 
public: 
    <...> 
    bool operator==(const CascadeJobInfo & other) const; 
    <...> 
}; 

bool CascadeJobInfo::operator==(const CascadeJobInfo & other) const 
{ 
    if (this == &other) { 
     return true; 
    } 

    bool equal = <...compare each data member within this object with its counterpart in other...>; 
    return equal; 
} 

official documentation说,很清楚:

This function requires the value type to have an implementation of operator==().

而且,目前尚不清楚你想从您的代码段达到的目标。尝试在遍历列表时删除每个列表的项目有一个更简单的替代方法:方法clear()

+0

I想要删除当前的项目“jobInfo” 不想删除整个项目 – Sijith

1

你不问如何从列表中删除“一个”对象,但如何删除所有对象。使用clear()

m_InternJobInfoList.clear(); 

如果你问如何删除了其中一些谓词是真实的,只有对象,你想使用erase代替:

auto & list = m_InternJobInfoList; 
auto const pred = [](const CascadeJobInfo &){ return true; }; 
list.erase(std::remove_if(list.begin(), list.end(), pred), list.end()); 

当然pred中可以做更多的事情有用。

future C++和Qt,希望你将能够简单地做

erase_if(list, pred); 
+0

感谢您的详细解释,但代码看起来很复杂,如果jobinfo中的一个参数匹配我的成员varable – Sijith

+0

我不想删除特定对象“jobInfo”我不是理解你给出的代码,如何删除特定的对象形式列表 – Sijith

+0

@Sijith,你可能需要熟悉[erase-remove idiom](https://en.wikipedia.org/wiki/Erase%E2%80) %93remove_idiom)。如果你是,这个答案应该清楚... – Mike