如何从向量中删除struct元素? [英] How to remove a struct element from a vector?
问题描述
我是一个新手程序员,我正在一个程序,在一个酒店(在我们在课堂上看到的一些愚蠢的运动,注册表)没有关系。我使用向量来保存结构元素(宠物)。结构的代码如下:
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 holding the struct elements (pets). The code for the struct is this:
struct Pets{
string Name;
string Race;
string Owner;
int Tel;
}p;
要求用户输入的功能是:
And the function to ask for user input is this:
AddPet(vector<Pets> &vtnew)
{
Pets newpet;
cout << "Enter the pet's name: " << endl;
cin >> newpet.Name;
cout << "Enter the pet's race: " << endl;
cin >> newpet.Race;
cout << "Enter the owner's name: " << endl;
cin >> newpet.Owner;
cout << "Enter the owner's telephone number: " << endl;
cin >> newpet.Tel;
vtnew.push_back(newpet);
}
好,现在我需要创建一个函数来删除宠物名称或某事。有没有办法做到这一点?
Ok, now I need to create a function to remove the pet by entering the name or something. Is there any way to do that?
推荐答案
向量是一个未排序的容器,所以简单的解决方案是真正唯一的选择。 / p>
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());
}
这称为 Erase-remove idiom 。
请注意,这会删除所有与该名称相符的宠物,不只是一个。
Note that this will remove all pets matching that name, not just one.
这篇关于如何从向量中删除struct元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!