当list队列中stu元素的name字段相同时,删除age字段较小的stu元素
#include<iostream>
#include<list>
#include<string>
using namespace std;
struct stu{
int age;
string name;
};
int main()
{
list<stu> li;
stu s1,s2,s3;
s1 = {20,"zhangsan"};
s2 = { 21, "lisan" };
s3 = { 22, "lisan" };
li.push_back(s1);
li.push_back(s2);
li.push_back(s3);
//li.unique();
//遍历输出
for (auto it:li)
{
cout << it.age << " " << it.name << endl;
}
auto iter = li.begin(); //容器起始
auto itend = li.end(); // 容器末尾
for (auto itcnt = iter; ++itcnt != itend; iter++)
{
for (auto itcmp = itcnt; itcmp != itend; itcmp++)
{
if (iter->name == itcmp->name)
{
if (iter->age > itcmp->age) //将小的删除
{
itcmp=li.erase(itcmp);//erase的返回值是删除元素下一个元素的迭代器
}
else
{
iter=li.erase(iter);
}
}
}
}
cout << "------去重后的元素------------" << endl;
for (auto it11 : li)
{
cout << it11.age << " " << it11.name << endl;
}
system("pause");
return 0;
}