std :: vector :: erase(item)需要为item定义操作符? [英] std::vector::erase(item) needs assignment operator to be defined for item?
问题描述
我有一个类 C
,它没有定义 operator =
。我试图使用像这样的向量: std :: vector< std :: pair< C,D> vec;
。现在,我的问题是,我不能擦除这对后,我完成它。编译器抱怨缺少 operator =
for C
。我不能有一个没有这个运算符的类的向量?如何解决这个问题?我无法向 C
添加分配。这是我得到的错误:
I have a class C
which does not define operator=
. I have am trying to use a vector like so: std::vector<std::pair<C,D>> vec;
. Now, my problem is that I am not able to erase the pair after I am done with it. The compiler complains of missing operator=
for C
. Can I not have a vector of a class which does not have this operator? How do I get around this? I cannot add assignment to C
. This is the error I get:
error C2582: 'operator =' function is unavailable in 'C' C:\...\include\utility 196 1 my-lib
这是我的代码:
void Remove(const C& c)
{
auto i = cs_.begin();
while( i != cs_.end()) {
if (i->first == c) {
cs_.erase(i); // this is the problem
break;
}
i++;
}
}
其中 cs _
是:
std::vector<std::pair<C,D>> cs_;
推荐答案
原因是擦除会重新分配对象擦除不同于 std :: vector :: end()
的位置。重新分配涉及复制。
The reason is that erase will reallocate your objects if you erase a different position than std::vector::end()
. A reallocation implicates copying.
请注意,不可复制类型的向量只能部分使用。在我们有 emplace()
(pre-C ++ 11)之前,这是不可能的。如果你的类是可复制的,为什么不定义一个赋值运算符呢?
Notice that a vector of an uncopyable type is only partially useable. Before we had emplace()
(pre-C++11) it was even impossible. If your class is however copyable, why dont you define an assignment operator then?
一个解决方法可以是一个smartpointer(或正常指针) > std :: vector< std :: unique_ptr< C>>
A workaround could be a vector of smartpointers (or normal pointers) like std::vector<std::unique_ptr<C>>
这篇关于std :: vector :: erase(item)需要为item定义操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!