【发布时间】:2018-12-18 20:39:32
【问题描述】:
在这个例子中,我构建了一个包含 4 个 Person 对象的 linked list,每个对象都有一个 age。我想遍历 Persons 列表,跟踪最年轻的人,然后从列表中删除该人。
这是我目前所拥有的
#include <iostream>
#include <vector>
#include <list>
struct Person
{
Person(int x): age(x) {}
int age;
};
int main() {
// Create 4 Person instances
Person p1 = Person(50);
Person p2 = Person(35);
Person p3 = Person(99);
Person p4 = Person(17);
// Build a list of persons
std::list<Person> persons = {p1, p2, p3, p4};
// Delete the list-element of the youngest person
int minAge = 999; // track the lowest age so far
Person* youngin = nullptr; // track the person with the lowest age so far
// Iterate through each person in the list, looking for someone with a lower age than all previous
for(auto const &p : persons){
if(p.age < minAge){
std::cout << "Found someone younger. Age: " << p.age << std::endl;
// Update minAge and youngin
minAge = p.age;
// youngin = ???;
}
}
// Delete the youngest person from the list
// persons.erase(youngin);
return 0;
}
我如何 1) 保留一个指向“迄今为止”最年轻的人的指针(我认为?),以及 2) 在最后从列表中删除该元素?
更新
看来我过于简化了我的最小可重现示例。 @NathanOliver 似乎对我的要求有最好的解决方案,所以我会选择他作为接受但如果有人愿意进一步帮助我,
假设有第 5 个人不在列表中,
Person p5 = Person(30);
现在,我如何确定列表中的 4 个人中哪一个的年龄与 p5 最接近,然后从列表中删除该人? (在这种情况下,p2 应该被识别并删除。)我不知道如何将 Nathan 的解决方案使用 std::min_element 应用于这种情况。
干杯
【问题讨论】:
标签: c++