我有class Passanger变量string name; string station; string ticket;
,然后我有另一个类,在这个类我有vector<Passanger*> myQueue;
现在我想stable_sort用来排序myQueue.有没有可能,怎么说stable_sort,什么应该是关键,根据它应该排序myQueue?
std::stable_sort(myQueue.begin(),myQueue.end(), maybeSomethingElse() ); ?
And*_*owl 13
有一个重载std::stable_sort()接受自定义比较器作为其第三个参数.你可以在那里提供一个比较函数,一个函子或一个lambda(在C++ 11中).以lambda为例,例如:
std::stable_sort(myQueue.begin(),myQueue.end(), [] (Passenger* p1, Passenger* p2)
{
return p1->age() < p2->age(); // Or whatever fits your needs...
});
Run Code Online (Sandbox Code Playgroud)
是的,你需要一个比较器类.它们看起来像这样.
class CompareFoo {
public:
bool operator() (const Foo* e1, const Foo* s2)
{
return e1->name < e2->name; // strict weak ordering required
}
};
Run Code Online (Sandbox Code Playgroud)
然后将其实例化作为参数传递给stable_sort.
std::stable_sort(myQueue.begin(), myQueue.end(), CompareFoo());
Run Code Online (Sandbox Code Playgroud)