jeudi 8 juillet 2021

Removing classes from an array C++

I have a vector array for classes and im making a method that can delete the classes from that array, using std::remove(). The problem is Weapon (the class) doesn't have an operator == that std::remove needs to compare the elements.

the code:

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";
    }
}

the error:

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 ==========

This is my first question! I hope everything is clear.

Aucun commentaire:

Enregistrer un commentaire