std :: sort获取std :: bad_alloc [英] std::sort getting a std::bad_alloc

查看:238
本文介绍了std :: sort获取std :: bad_alloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is wrong with the sort() above? I am getting a:

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

gdb没有给我任何有用的东西...

when I call sort(). gdb isn't giving me anything useful either...

我认为这个问题与因为我在一个类中有关?

I presume the problem has something to do with cause I am in a class?

编辑:解决

问题是这一行

      return a.second >= b.second;

更改为

      return a.second > b.second;


推荐答案

std :: sort 必须建立严格弱排序。这意味着:

The comparator you give to std::sort must establish a strict weak ordering. That means:


  • 对于所有x,不是compare(x,x)(irreflexivity)。

  • 对于所有x≠y,如果compare(x,y),则不是compare(y,x)(不对称)。

  • 对于所有x ,y和z,如果比较(x,y)和比较(y,z),则比较(x,z)(传递性)。
  • 对于所有x,y和z ,如果x与y无法比较,并且y与z无法比较,则x与z(等价的传递性)无法比较。
  • For all x, it is not the case that compare(x, x) (irreflexivity).
  • For all x ≠ y, if compare(x, y) then it is not the case that compare(y, x) (asymmetric).
  • For all x, y, and z, if compare(x, y) and compare(y, z) then compare(x, z) (transitivity).
  • For all x, y, and z, if x is incomparable with y, and y is incomparable with z, then x is incomparable with z (transitivity of equivalence).

您的原始比较器不是无反射的: compare(x,x)是true。使用这样的比较器会导致未定义的行为,您首先遇到 std :: bad_alloc

Your original comparator is not irreflexive: compare(x, x) is true. Using such a comparator results in undefined behaviour, which you experienced first-hand as a std::bad_alloc.

这篇关于std :: sort获取std :: bad_alloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆