How to remove a struct element from a vector?

后端 未结 1 1106
名媛妹妹
名媛妹妹 2021-01-23 02:06

I\'m a newbie programmer and I\'m working on a program that holds a registry of pets in a hotel (some silly exercise we saw in class, doesn\'t matter). I\'m using vectors for ho

相关标签:
1条回答
  • 2021-01-23 02:38

    A vector is an unsorted container so the simple solutions are really your only choice.

    void RemovePet(std::vector<Pet> & pets, std::string name) {
        pets.erase(
            std::remove_if(pets.begin(), pets.end(), [&](Pet const & pet) {
                return pet.Name == name;
            }),
            pets.end());
    }
    

    This is known as the Erase-remove idiom.

    Note that this will remove all pets matching that name, not just one.

    0 讨论(0)
提交回复
热议问题