调用std :: stable_sort时出错?

时间:2010-09-20 14:21:31

标签: c++ sorting stl

struct SimGenRequest {

    int wakeup_mfm_;
    double value_;

    bool operator < ( const SimGenRequest & r2 ) const 
        { return ( wakeup_mfm_ < r2.wakeup_mfm_ ) ; }

};

使用:

std::stable_sort ( all_requests_.begin ( ), all_requests_.end ( ) );

作品(编译)。但是

struct SimGenRequest {

    int wakeup_mfm_;
    double value_;

};

bool CompareByWakeTime ( const SimGenRequest & r1, const SimGenRequest & r2 ) {
    return ( r1.wakeup_mfm_ < r2.wakeup_mfm_ ) ;
}

使用:

std::stable_sort ( all_requests_.begin ( ), all_requests_.end ( ), 
    CompareByWakeTime );

不起作用。 有什么指针吗?

2 个答案:

答案 0 :(得分:0)

以下是您的代码或多或少。它编译并产生预期的输出。为了进一步帮助您,我们需要更多关于什么不起作用的信息。

#include <algorithm>
#include <iostream>
#include <set>
#include <vector>

struct SimGenRequest {

    int wakeup_mfm_;
    double value_;

    SimGenRequest(int w, double v) :
        wakeup_mfm_(w),
        value_(v)
    { }
};

bool CompareByWakeTime ( const SimGenRequest & r1, const SimGenRequest & r2 ) {
    return ( r1.wakeup_mfm_ < r2.wakeup_mfm_ ) ;
}

int main()
{
    std::vector<SimGenRequest> all_requests_;

    all_requests_.push_back(SimGenRequest(3, 1));
    all_requests_.push_back(SimGenRequest(4, 3));
    all_requests_.push_back(SimGenRequest(3, 2));
    all_requests_.push_back(SimGenRequest(1, 4));

    std::stable_sort(all_requests_.begin(), all_requests_.end(), CompareByWakeTime);

    for(std::vector<SimGenRequest>::const_iterator i = all_requests_.begin();
        i != all_requests_.end();
        ++i)
    {
        std::cout << '(' << i->wakeup_mfm_ << ", " << i->value_ << ')' << std::endl;
    }
    return 0;
}

答案 1 :(得分:-1)

STL使用onle运算符减少重载。否则,您可以为排序指定任何布尔函子,但您必须在stable_sort调用时输入它。