2012-02-07 101 views
1
class RankList { 
public: 
    struct RankListComparator { 
    bool operator()(const std::pair<boost::numeric::ublas::vector<double>, double>& a, const std::pair<boost::numeric::ublas::vector<double>, double>& b) { 
     return a.second >= b.second; 
    } 
    }; 

    void push_back(boost::numeric::ublas::vector<double> features, double label) { 
    m_list.push_back(std::pair<boost::numeric::ublas::vector<double>, double>(features, label)); 
    } 

    void sort() { 
    std::sort(m_list.begin(), m_list.end(), RankListComparator()); 
    } 

protected: 
    std::vector<std::pair<boost::numeric::ublas::vector<double>, double> > m_list; 
}; 

上面的sort()有什麼問題?我得到一個:std ::排序獲取std :: bad_alloc

terminate called after throwing an instance of 'std::bad_alloc' 
    what(): std::bad_alloc 

當我調用sort()。 gdb是不給我任何有用的...

我認爲這個問題有關係,因爲我在一個類中?

編輯:解決

問題是這條線

 return a.second >= b.second; 

改爲

 return a.second > b.second; 

回答

6

你給std::sort必須建立strict weak ordering比較。這意味着:

  • 對於所有x,它不是比較(x,x)(irreflexivity)的情況。
  • 對於所有x≠y,如果比較(x,y),則不是比較(y,x)(不對稱)的情況。
  • 對於所有x,y和z,如果比較(x,y)和比較(y,z),則比較(x,z)(傳遞性)。
  • 對於所有的x,y和z,如果x與y不可比,且y與z不可比,那麼x與z(等價的傳遞性)是無法比擬的。

您的原始比較器不是無反射的:compare(x, x)爲true。使用這樣的比較器會導致未定義的行爲,您將親身經歷爲std::bad_alloc