c++ - <链表C ++中结构成员的运算符重载
问题描述
所以基本上我有我的结构,它在将数据分配给链表的值之前保留数据,并帮助我稍后检索它
struct Student
{
private:
string surname ;
string names ;
int index;
float mark;
}
这是我插入排序链表的实现
template<typename T>
void List<T>::insert(T v)
{
Node* pred = nullptr;
Node* succ = head;
while(succ != nullptr && succ->value < v) <- here
{
pred = succ;
succ = succ->next;
}
...
我的问题是我需要按索引对其进行排序,而我的 < 运算符重载的实现似乎都不起作用
bool operator<(const Student&){
return next->index < this->index;}
我正在对 == 或 + 之类的运算符进行一些重载,但从不 <,有人可以给我建议它的外观吗?
解决方案
index
是private
,这意味着您需要将其设为成员函数或将其声明为friend
.
struct Student {
bool operator<(const Student& other) const {
return index < other.index;
}
private:
string surname;
string names;
int index;
float mark;
};
您可以指定this->index
而不是 just index
,但大多数时候这不是必需的。
另外,作为旁注,如果您使用的是 C++ 20,我建议重载spaceship 运算符,因为这将自动为所有比较运算符(和除外)生成适当的定义:==
!=
auto operator<=>(const Student& other) {
return index <=> other.index;
}
推荐阅读
- objective-c - Xcode tvOS - 如何检测何时按下电视遥控器上的菜单按钮?
- oracle - 这个物化视图可以快速刷新吗?
- python - Python 新手,难以理解特定代码
- angular - 使用 Mat-sort-header
- rest - struts2-rest-plugin 与 struts2-json-plugin 有何不同
- c# - Unity - 在 UI 文本上显示变量
- python - 带有 Selenium 的 Python 谷歌翻译错误
- jquery - 我如何删除“rtable”表中除前 2 个之外的所有 tbody 元素
- c# - 在 Unity C# 中修复拉伸网格法线?
- python - How to fix IndexError: list index out of range while scraping