Mistake in calling std::stable_sort?
struct SimGenRequest {
int wakeup_mfm_;
double value_;
bool operator < ( const SimGenRequest & r2 ) const
{ return ( wakeup_mfm_ < r2.wakeup_mfm_ ) ; }
};
Use :
std::stable_sort ( all_requests_.begin ( ), all开发者_Python百科_requests_.end ( ) );
Works ( compiles ). But
struct SimGenRequest {
int wakeup_mfm_;
double value_;
};
bool CompareByWakeTime ( const SimGenRequest & r1, const SimGenRequest & r2 ) {
return ( r1.wakeup_mfm_ < r2.wakeup_mfm_ ) ;
}
Use :
std::stable_sort ( all_requests_.begin ( ), all_requests_.end ( ),
CompareByWakeTime );
does not work. Any pointers ?
The following is more or less your code. It compiles, and produces the expected output. To further help you, we need more information as to what isn't working.
#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;
}
STL uses onle operator less overloading. Otherwise you can specify any boolean functor for the sort, but you have to input it at the stable_sort call.
精彩评论