如何在模板类中重载较少运算符以供排序算法使用
How to overload less operator in a template class for sort algorithm use?
我有一个使用模板的自定义类,如下所示:
template<class T>
class foo
{
public:
T a;
bool operator<(const foo<T> &f);
//other functions...
}
template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a - f.a;}
现在,我新建了一些 foos 并赋予它们值,然后我想对这个数组进行排序:
foo<int>* fp = new foo<int>[3];
//give each element value
sort(fp, fp+3); //run-time error
当我使用排序函数时,我遇到了运行时错误。
我做错了什么吗?请帮助我。
大概是这样的:
template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a < f.a;}
std::sort
要求比较函数(在本例中为小于运算符)定义严格的弱排序。您的实现不会,因为A < B
和B < A
都可能为真。
如果 T 可投射到布尔值,
template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a - f.a;}
将始终返回 true,除了 == f.a。也许你需要这样的东西:
template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a < f.a;}
显然,发生运行时错误是因为您的 less 运算符对排序函数不正确。
相关文章:
- 使用运算符+将两个已排序的链表合并到位
- 尝试使用比较运算符对对象向量进行排序
- 更大的运算符">"满足严格的弱排序吗?
- STL按客户"<"运算符对向量进行排序。为什么要将"<"运算符定义为 const?
- 使用运算符覆盖排序没有得到我想要的
- 运算符重载在 CPP 中的排序中如何工作?
- 对于列表排序,有没有办法使用相同的参数让多个运算符重载?
- 使用赋值运算符功能按距离对数组对象进行排序
- 重载小于 (<) 运算符,用于以多种方式对对象进行排序
- 排序向量<变体<...>>无法通过运算符正常工作<
- 是否有使用 c++ &&(AND) 运算符排序
- C++11(排序)中的逗号运算符
- 运算符<用于列表排序
- 如何在模板类中重载较少运算符以供排序算法使用
- 排序中的<运算符断言无效
- C++类指针的排序与重载运算符<
- 使用较少STL运算符对点进行排序
- 排序运算符在C++中不起作用
- 试图使用重载C++的运算符按字母顺序对图书向量进行排序
- C++ - 排序算法看不到用户定义类型的重载"<"运算符。