Can I pass a parameter to an std::vector sort function?

c++, sorting, stl, vector

Solution

class sorter {
      short type_;
public:
      sorter(short type) : type_(type) {}
      bool operator()(MyClass const* o1, MyClass const* o2) const {
            return SortFunction(o1, o2, type_ );
      }
};

std::sort(Vec.begin(), Vec.end(), sorter(MY_TYPE) );

Problem

Consider the class: ``` MyClass { int varA; int varB; }; ``` I have a vector of pointers to MyClass objects: ``` std::vector<MyClass*> Vec; ``` I want to sort the vector according to varA or varB using the same sort function, i.e. : ``` bool SortFunction(const MyClass* obj1, const MyClass* obj2, const short type) { if( type == VARA_ID ) return obj1->varA < obj2->varA; else if( type == VARB_ID ) return obj1->varB < obj2->varB; } ``` AFAICT this is not possible. What would be the most elegant way to this without using external libraries?

Original source