std :: sort获取std :: bad_alloc

时间:2012-02-07 02:05:58

标签: c++ sorting

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()有什么问题?我得到了:

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;

1 个答案:

答案 0 :(得分:6)

您提供给std::sort的比较器必须建立strict weak ordering。这意味着:

  • 对于所有x,不是比较(x,x)(反射性)的情况。
  • 对于所有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)为真。使用这样的比较器会导致未定义的行为,您亲身体验过std::bad_alloc

相关问题