假设我们写一个Person类,类中有年龄,姓名和身高三个属性,这时我们想在list容器中删除这个Person类,需要用到remove()函数,但是不能直接调用remove。我们看到remove函数的定义
list<_Tp, _Alloc>::remove(const value_type& __x)
{
list<_Tp, _Alloc> __deleted_nodes(get_allocator()); // collect the nodes we're removing
for (const_iterator __i = begin(), __e = end(); __i != __e;)
{
if (*__i == __x)
{
const_iterator __j = _VSTD::next(__i);
for (; __j != __e && *__j == __x; ++__j)
;
__deleted_nodes.splice(__deleted_nodes.end(), *this, __i, __j);
__i = __j;
if (__i != __e)
++__i;
}
else
++__i;
}
return (__remove_return_type) __deleted_nodes.size();
}
核心就是第一个if的== 运算符,所以我们需要重载==运算符。不同编译器有不同特点,如果报错需要注意
- 在类外重载 == 运算符
- 用const修饰Person变量
写法如下:
class Person
{
public:
Person(string name, int age, int height)
{
this->m_Age = age;
this->m_Name = name;
this->m_height = height;
}
string m_Name;
int m_Age;
int m_height;
};
// 类外重载==让remove可以删除自定义的Person类型
bool operator==(const Person &p1, const Person &p2)
{
if(p1.m_Age == p2.m_Age && p1.m_height == p2.m_height && p1.m_Name == p2.m_Name)
return true;
return false;
}
void test03()
{
list<Person>l;
Person p1("张三", 10, 172);
Person p2("张三", 19, 145);
Person p3("张三", 15, 181);
Person p4("张三", 20,199);
Person p5("张三", 19, 171);
Person p6("张三", 19, 179);
l.push_back(p1);
l.push_back(p2);
l.push_back(p3);
l.push_back(p4);
l.push_back(p5);
l.push_back(p6);
l.remove(p3);
}