c++ - 使用模板时如何从 std::vector 中删除元素?

标签 c++ templates vector

我有一个相当简单的模板类,我在其中将项目存储在 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/

相关文章:

html - Meteor 模板强制为 HTML

vector - Clojure HashMap 作为广义向量

c++ - directx 11 基于旋转移动对象

c++ - 如何强制 operator>>(C<T>) 重载以匹配容器?

c++ - "invalid initialization of non-const reference of type..."clone()函数出错

java - 尽管行数超过 1,但 JTable 仅显示 1 行

math - 从两点和方向向量计算角度

c++ - 我可以在 "for"循环中有两个初始化语句吗?

c++ - 具有非模板基类的模板类

python - python3中的编码/解码(Berkeley数据库记录)