c++ 将非零偏移量4应用于空指针[已关闭]

xa9qqrwz  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(246)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
20小时前关门了。
Improve this question
一些球形气球贴在代表XY平面的平面墙上。气球表示为2D整数数组点,其中points [i]=[xstart,xend]表示水平直径在xstart和xend之间伸展的气球。您不知道气球的确切y坐标。
箭头可以从x轴上的不同点直接垂直向上(在正y方向上)发射。如果xstart〈= x〈= xend,则具有xstart和xend的气球会被在x处发射的箭头爆破。可以发射的箭头的数量没有限制。发射的箭头会无限地向上移动,从而爆破其路径上的任何气球。
给定数组点数,返回必须发射以爆破所有气球的最小箭头数

bool compare(vector<int> &a,vector<int> &b){
          return a[1]<=b[1];
}
class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        if(points.size()==1) return 1;
        sort(points.begin(),points.end(),compare);
        int arrows=1,end=points[0][1];
        for(int i=1;i<points.size();i++){
            if(points[i][0]>end){
                arrows++;
                end=points[i][1];
            }
        }
        return arrows;
    }
};

我收到运行时错误:

Line 1034: Char 34: runtime error: applying non-zero offset 4 to null pointer (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
e0bqpujr

e0bqpujr1#

bool compare(vector<int> &a,vector<int> &b){
          return a[1]<=b[1];
}

应该是

bool compare(const vector<int> &a, const vector<int> &b){
          return a[1]<b[1];
}

比较器必须定义一个 strict weak ordering。这样做的一个结果是,对于相等的值,它们必须返回false,所以<=是不正确的。
但是,通过查看错误消息,我怀疑问题的直接原因是向量points的大小为零,因此end=points[0][1]是一个越界向量访问。

相关问题