我有一个相当简单的模板类,我在其中将项目存储在 vector 中。但是,当我尝试删除元素时出现以下错误:
C2678: binary '==': no operator found which takes a left-hand operand of type
'TestComponent' (or there is no acceptable conversion)
这是我使用的代码:
#pragma once
#include <vector>
template<class T>
class ComponentManager {
ComponentManager() {};
~ComponentManager() {};
T* newComponent() {
components.emplace_back(T());
return &components.back();
}
// This is the method I'm having trouble with
void destroyComponent(T* t) {
components.erase(std::remove(components.begin(), components.end(), *t), components.end());
}
private:
std::vector<T> components;
};
是的,我知道这会导致指针无效等等。不需要去那里。
最佳答案
如果您试图通过指针删除,您需要为此使用正确的算法。 std::remove
在元素之间进行相等比较。根据您的评论,您不想要求这样做,因此您可能更喜欢 std::remove_if
相反:
void destroyComponent(T* t) {
components.erase(
std::remove_if(components.begin(), components.end(), [t](const T& comp) {
return &comp == t;
}),
components.end()
);
}
请注意,将指针保存到 vector
中并不是特别安全因为插入 vector 可能会导致重新分配,这会使所有先前持有的指针无效。您可能需要考虑一个不同的容器(或者只是有一个 vector<T*>
或者更好的是 vector<unique_ptr<T>>
)。
关于c++ - 使用模板时如何从 std::vector 中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36337062/