Pau*_*nto 13 c++ sorting stl vector
考虑班级:
MyClass {
int varA;
int varB;
};
Run Code Online (Sandbox Code Playgroud)
我有一个指向MyClass对象的指针向量:
std::vector<MyClass*> Vec;
Run Code Online (Sandbox Code Playgroud)
我想使用相同的排序函数根据varA或varB对向量进行排序,即:
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;
}
Run Code Online (Sandbox Code Playgroud)
AFAICT这是不可能的.如果不使用外部库,最优雅的方法是什么?
Own*_*loo 21
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) );
Run Code Online (Sandbox Code Playgroud)
你差不多了,做type一个模板参数,签名就可以了:
template<int type>
bool SortFunction(const MyClass* obj1, const MyClass* obj2) {
if( type == VARA_ID )
return obj1->varA < obj2->varA;
else // if( type == VARB_ID ) -- A sort function must have a default.
return obj1->varB < obj2->varB;
}
std::sort(Vec.begin(), Vec.end(), &SortFunction<VARA_ID> );
Run Code Online (Sandbox Code Playgroud)
优化器将发现这( type == VARA_ID )是一个编译时常量.