2012-02-07 81 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