1.如果要用vector存储自定义类型数据,需要类重载运算符。如下
class A{
public:
A(){}
~A(){}
friend bool operator==(const A& a1, const A& a2)
{
return (a1.a==a2.a)?true:false;
}
// or
/*
bool operator==(const Convertable& other)
{
return a==other.a;
}
*/
private:
int a;
};
2.map实现存储自定义类型
class A{
public:
A(){}
~A(){}
bool operator<(const A& a1) const{
return (a<a1.a)?true:false;
}
// or
// friend bool operator<(const A& loc1, const A& loc2)
// {
// return (loc1.a < loc2.a) ? true : false;
//}
private:
int a;
};
本文介绍了如何在C++中为自定义类型重载运算符以适应STL容器,如vector和map。通过重载`==`运算符确保在vector中正确比较元素,以及重载`<`运算符使自定义类型能在map中作为键使用。理解这些操作对于高效利用STL容器存储自定义类型数据至关重要。
9113

被折叠的 条评论
为什么被折叠?



