I have a uni assignment / project (Data Structures class), where I have to implement the ins-n-outs of 1D arrays, by creating a dynamically allocated array class, which can accept any type of data (using templates). But there's a problem.

I'd like to implement sorting the elements of the array. But given the fact, that I'm using templates, I cannot treat the elements as integers, nor as strings, or other types...
Also, let's say that the elements of the array are elements of class T, where T looks like this:

class T {
double height;
int age;
string name;
double getH() { return height; }
int getAge() { return age; }
string getName() { return name; }

(It's just a random example, pls don't judge for code quality...)

Let's say that I'd like to sort the T elements based on height, print out, sort by age, print out, then sort by name and print out. How can I do this? Is this possible?

  • 1
    I'd say do not implement a sorting algo as a part of a generic array. For some types, comparison might not make sense, so why make it part of the class?

    If you still have to do it, look at how std::sort is implemented. Use less-than operator by default to compare the elements, and add an overload that takes a comparison function - then the user will be able to define how two objects are compared.
  • 0
    @Kodnot Yeah, I thought about that, I just hoped, that there's sort of a "magic" C++ mechanism, that could help me... 🙂
  • 0
    @irene That's an interesting idea - I might implement sorting just for numeric types (int, float, etc), and call it a day... 😅
  • 1
    @tomiolah1998 passing a comparison function is a good solution IMO. That way you give a lot of customisation options to the user. I don't believe any other mechanism, magical or not, would be that flexible ☺

    @irene a nice suggestion, but it won't suffice for the OP's example, as he wants multiple sort variations for the same type ☺
  • 1
    @tomiolah1998 That would be a bad practice. If you do that, then you should restrics the type to numeric types only
  • 1
    The std::map and other ordered class take a comparator or equality template type. You would take something like that. Operator overloading is another way to achieve this. I would recommend that approach. It’s ok for it to throw compiler errors if the user hasn’t specified a way to compare things.

    Another way I’ve dealt with it is just static symbols. Have a global scope comparator function that’s overloaded for each type if you want to only have predetermined types.

    Otherwise I would just use an existing ordering operator and assume the user must provide a type that has that operator defined.
  • 1
    @irene search operator overloading. That’s the real way to do this.
  • 0
    @irene “google” operator overloading in c++
Your Job Suck?
Get a Better Job
Add Comment