Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
Kodnot4647yI'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. -
@Kodnot Yeah, I thought about that, I just hoped, that there's sort of a "magic" C++ mechanism, that could help me... 🙂
-
@irene That's an interesting idea - I might implement sorting just for numeric types (int, float, etc), and call it a day... 😅
-
Kodnot4647y@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 ☺ -
Kodnot4647y@tomiolah1998 That would be a bad practice. If you do that, then you should restrics the type to numeric types only
Related Rants
-
xjose97x19Just saw a variable in C named like this: long time_ago; //in a galaxy far away I laughed no stop.
-
Cyborg15A guy and a girl are in a Java seminar. Afterward, the guy approaches the girl and asks, "Hey gurrl, can I ge...
-
Unskipp24So this happened last night... Gf: my favorite bra is not fitting me anymore Me: get a new one ? Gf: but it ...
!rant
C++ / OOP QUESTION
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 {
private:
double height;
int age;
string name;
public:
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?
question
data
structures
project
assignment
template
uni
oop
c++
sort
class