2010-09-20 63 views
2
struct SimGenRequest { 

    int wakeup_mfm_; 
    double value_; 

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

}; 

用途:調用std :: stable_sort時出錯?

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); 

不起作用。 任何指針?

+6

「不起作用」是什麼意思?不,這個代碼中沒有指針(儘管迭代器可能是指針的typedef)。 – 2010-09-20 14:25:18

+0

第二個變體編譯爲我,假設需要include和std :: set all_requests_; – 2010-09-20 14:30:38

+1

@Steve Townsend:我懷疑它是用'std :: set'編譯的 - 你的意思是'std :: vector'? (在集合上調用'std :: stable_sort'毫無意義,實際上它不會被編譯!)否則,它也會爲我編譯。 – Thanatos 2010-12-05 20:38:58

回答

-1

STL使用onle運算符更少的重載。否則,您可以爲排序指定任何布爾函子,但必須在stable_sort調用中輸入它。

+1

這不是OP想要做什麼? – Thanatos 2010-12-05 20:32:50

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; 
}