Generic sorting of multidimensional objects

Hi,

I have a class that contains four data members, i.e.,
1
2
3
4
5
6
7
8
9
	class ClassA
	{
		...
		private:
			int property1;
			int property2;
			int property3;
			int property4;
	};

I create a vector of these objects which I need to sort by any combination of these properties (one or more) in a generic way. For example, something like:

1
2
3
4
void sortByOneProperty(std::vector<ClassA*>& vec, ...property...);
void sortByTwoProperties(std::vector<ClassA*>& vec, ...property..., ...property...);
void sortByThreeProperties(std::vector<ClassA*>& vec, ...property..., ...property..., ...property...);
void sortByFourProperties(std::vector<ClassA*>& vec, ...property..., ...property..., ...property..., ...property...);


The solution has to be generic enough to avoid enumerating all possible combinations of sorting properties into respective "void sort...(...)" functions.

Any ideas?
Chris
If all properties are of the same type and the type implements operator<, you could do it by using memory pointers, a small functor and the std::sort() function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
struct Props
{
    int prop1;
    int prop2;
    int prop3;
    int prop4;
};

class ClassA
{
private:
    Props _props;
public:
    //Index is zero-based.
    bool CompareTo(int index, const ClassA &other)
    {
        //CORRECTION HERE!!!
        int &myVal = *(&_props + index);
        int &otherVal = *(&other._props + index);
        return ( myVal < otherVal);
    }
};

class CompareFunctor
{
private:
    int _propIndex;

public:
    CompareFunctor(int propIndex) : _propIndex(propIndex)
    { }
    bool operator()(const ClassA &op1, const ClassA &op2)
    {
        return op1.CompareTo(_propIndex, op2);
    }
};

.....
//Now, whenever you need to sort, you do:
typedef std::vector<ClassA> ClassACollection;
ClassACollection someCollection;
//Fill the collection up.
...
std::sort(someCollection.begin(), someCollection.end(), CompareFunctor(theIndexPropertyGoesHere));
Last edited on
Thanks webJose. This is a pretty elegant solution!
Chris
NP. See the small correction I did to the code. I was comparing pointers and not the values pointed to by the pointers.
Sure. Thanks a lot!
Chris
Topic archived. No new replies allowed.