I'm new to C++ but I do understand the basics of programming. I've recently started getting serious and intend to go "pro" with it.
I made a template LinkedList that can accept any kind of data. For my assignment we have to make a base class called Vehicle, and two derived classes called Car and Truck. One of the things we have to do is to sort the lists in different ways, according to the user's input.
My classmates are just as puzzled, if not more, so we're trying to figure this out (our assignments are always beyond what they teach us).
I thought of two ways to do it, but they're not very "nice":
- One way is to use a function as a parameter to the sorting of the list. Eg a compare_passengers(Vehicle &a, Vehicle &b) function that is passed on to the sort method of the LinkedList class.
- The other way is to have a static member called compare_key that determines which member of the class the overloaded operator > will compare. Eg:
(I didn't check the above code for syntax errors, so i I did something stupid it doesn't matter, this is just an example).Code:
bool Vehicle::operator > (Vehicle &other)
return this->passengers > other.passengers;
I don't like either of my solutions. They are not nice in a programming way, or user friendly. What I'd like to have is something like this:
Or, maybe, you have a better suggestion.Code:
//....adding elements to the list...
list.sort(Vehicle::get_passengers()) //sorts according to get_passengers()
list.sort(Vehicle::year) //sorts according to year, which is an integer
I'm sorry if this has been asked before, but I didn't even know what to search for besides "sorting" (which didn't give any good results).
Thanks in advance!
Edit: I forgot to mention that we are not allowed to use standard containers; we have to make our own.