-1

So basicaly I have my struct that keeps data before assigning it to value of linked list and helps me to retrieve it later

struct Student
{

private:

    string surname ;
    string names ;
    int index;
    float mark;
}

and here is my implementation of inserting into sorted linked list

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;
    }
...

my problem is i need to sort it by index and none of my implementations of < operator overloading seems to work

bool operator<(const Student&){
    return  next->index < this->index;}

I was doing some overloading on operators like == or + but never <, can anyone give me advice how it should look?

Adivin PL
  • 27
  • 2
  • 1
    Can you [edit] your question, and replace all isolated code snippets with a single, complete [mre] that everyone else can cut/paste ***exactly as shown*** into an empty file, then compile, run, and reproduce your problem? What does "none of my implementations ... seems to work" mean? – Sam Varshavchik Sep 09 '21 at 00:43
  • 1
  • 1
    Handy reading on operators across the board: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user4581301 Sep 09 '21 at 01:05
  • Could you add an explanation of how/why you believe your `operator – JaMiT Sep 09 '21 at 01:35
  • For a problem description as detailed as *"none [...] seems to work"*, the answer "because they had bugs" seems to be at about the same level of helpfulness. What led you to the conclusion that the version of `operator – JaMiT Sep 09 '21 at 04:10

1 Answers1

0

index is private, meaning you need to either make it a member function or declare it as a friend.

struct Student {

    bool operator<(const Student& other) const {
        return index < other.index;
    }

private:
    string surname;
    string names;
    int index;
    float mark;
};

You can specify this->index instead of just index, but most of the time that isn't necessary.

Also, as a side note, if you're using C++ 20, I recommend overloading the spaceship operator instead, as that will automatically generate appropriate definitions for all the comparison operators (except == and !=):

    auto operator<=>(const Student& other) {
        return index <=> other.index;
    }
Ætérnal
  • 197
  • 1
  • 4
  • *"you need to either make it a member function or [...]"* -- given that the question's version shows only one parameter for this *binary* operator, I would guess that it already is a member function. Similar setup to how you presented `operator<=>`, no? (Of course, if you don't like guessing, you could ask for clarification before answering.) – JaMiT Sep 09 '21 at 04:03