Advertisement

Searching with custom data

Started by January 26, 2016 12:59 PM
2 comments, last by Azzazelus 8 years, 10 months ago

Hello. I've made a vector class (an realizable array but moving the array when it gets bigger etc..) and Im using templates to pass any object type like this :


 
template<typename ElemType>
class   XVector {
 
}
 
struct myStruct {
int ID;
string name;
etc..
}
 
XVector<myStruct> myVector;

I made a search and a sort functions (in the XVector class) that takes the elements and compare them and in order for that to work I must overload the operators on myStruct so it can know what == or < means. So far so good but there are times when I need to sort the vector only on specific criteria for example only by ID and not by name; So instead of operator overloading I made function pointers in the class that are comparing.


int Compare(myStruct &elem1, myStruct &elem2 {
 compare by elem1.id etc..
}
 

I make outside functions and pass them to the vector object function pointer.

Is that a normal thing to do or t here are better solutions? I'm not intersted in STL yet.

Thanks.


I'm not intersted in STL yet.

Yet, you're reinventing STL, by doing everything exactly same way as it's already done in STL.

STL algorithms (namely 'sort') accept predicate function, or functor object with operator() defined.

Advertisement

Before you get to deep down that path maybe you should look at the FBVector before even worrying about sorting. If you are hand-rolling your own, I assume that you are also trying to defeat efficiency opportunities that std::vector leaves laying around (they are mentioned in that link). If you aren't doing it for those reasons then why? I am just curious.

I would also assume that though at some point you will *want* to use the STL. If that is the case, do you really want to have a mashup of STL and non-STL sorting methods? I really don't think so speaking from a place that had literally that kind of shiz as it is a complete cluster mess.

I was doing it for learning purpose. I was taking a course where the teacher implemented a custom Vector class just to see how things work "under the hood".

This topic is closed to new replies.

Advertisement