微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从数组 C++ 中删除类

如何解决从数组 C++ 中删除类

我有一个用于类的向量数组,我正在制作一个可以使用 std::remove() 从该数组中删除类的方法。问题是武器(类)没有 std::remove 需要比较元素的运算符 ==。

代码

class Weapon {
public:
    std::string name;
    Weapon(std::string x) {
        name = x;
    }
    Weapon() {}
};

std::vector<Weapon> inventory{};

void removeInventory(Weapon x) {
    if (inventorySize != 0) {
        auto deleteFromInc = inventory.erase(std::remove(std::begin(inventory),std::end(inventory),x),std::end(inventory));
        if (deleteFromInc != std::end(inventory)) {
                std::cout << "Item didn't delete\n";
        } else {
            if (heldWeapon.name == x.name) {
                heldWeapon = Weapon();
            }
            inventorySize = inventory.size();
            std::cout << "Item deleted\n";
        }
    } else {
        std::cout << "You have no items\n";
    }
}

错误

Rebuild started...
1>------ Rebuild All started: Project: rpag,Configuration: Debug Win32 ------
1>rpag.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xmemory(1945,1): error C2678: binary '==': no operator found which takes a left-hand operand of type 'Weapon' (or there is no acceptable conversion)
1>C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\guiddef.h(192,15): message : Could be 'bool operator ==(const GUID &,const GUID &)' [found using argument-dependent lookup]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xmemory(1945,1): message : while trying to match the argument list '(Weapon,const _Ty)'
1>        with
1>        [
1>            _Ty=Weapon
1>        ]
1>C:\Users\alber\source\repos\rpag\rpag\rpag.cpp(89): message : see reference to function template instantiation '_FwdIt std::remove<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<_Ty>>>,Weapon>(_FwdIt,const _FwdIt,const _Ty &)' being compiled
1>        with
1>        [
1>            _FwdIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Weapon>>>,1>            _Ty=Weapon
1>        ]
1>Done building project "rpag.vcxproj" -- Failed.
========== Rebuild All: 0 succeeded,1 Failed,0 skipped ==========

这是我的第一个问题!我希望一切都清楚。

解决方法

std::remove 需要 operator==(这是 C++ 标准库的要求)。您可以将运算符添加到您的类中,或者使用 std::remove_if - 它使用谓词 - 外部函数进行比较。

还有第三种方法:您可以手动从 vector 中擦除项目:for (...) { erase ...}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。