我正在使用Visual Studio 2012 C++,想将两个带有唯一指针的向量设置为相等。
using namespace std;
vector<unique_ptr<Unit>> unitVector;
vector<unique_ptr<Unit>> nonDeadUnits;
.... (stuff added to unitVector) ....
for (auto unit = unitVector.begin(); unit != unitVector.end(); ++unit) {
if ((*unit)->health > 0) {
nonDeadUnits.push_back(*unit);
}
}
unitVector.clear();
unitVector = nonDeadUnits; // error here (see below error code)
我想删除所有生命值小于0的单位,但是如果我尝试直接从向量中删除它们,我会尝试访问不应该访问的内存,导致程序崩溃。这就是为什么我选择这样做的原因。唯一的问题是unique_ptr不允许我想要的类型复制。以下是错误信息:
error C2248: 'std::unique_ptr<_Ty>::operator =' : cannot access private member declared in class 'std::unique_ptr<_Ty>' c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility 2089
我希望使用unique_ptr,因为后面的for循环中,向量调用子类方法会更方便进行覆盖。那么我该如何让这些向量相互等同呢?或者有更好的方法吗?
std::remove_if
可能对你有所帮助。我会尝试编写一个示例并将其发布为答案。 - QuuxplusoneunitVector = std::move(nonDeadUnits);
可以解决你的问题,但正如 Quuxplusone 所说,还有更好的解决方案。 - Mike Vine