我可以将参数传递给std :: vector排序函数吗?

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_参数,将其作为`std :: sort(...,sorter <MY_TYPE>())`传递.这消除了O(N log N)运行时检查. (6认同)

MSa*_*ers 6

你差不多了,做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 )是一个编译时常量.

  • 这个想法的+1,虽然我认为你的意思是说`template <short type>`而不是`template <typename type>`. (3认同)