【问题标题】:Segmentation error in vectors in C++C ++中向量中的分段错误
【发布时间】:2016-05-30 10:43:19
【问题描述】:

我有一个名为cpatches 的向量,它不是空的,并且至少包含一个对象cv::Point3i(0,0,0)。下面是我的代码,它给出了分段错误。代码运行良好,直到到达r2 = objects.front().y 行,然后出现分段错误并中止代码。

我正在尝试将由cv::Point3i(0,0,0) 分隔的对象分离到另一个名为objects 的向量。在排序中,compare_rowcompare_col 工作得非常好。 (它分别返回a.y > b.ya.z > b.z

代码如下。

for (int i = 0; i < cpatches.size(); i++) {
    cv::Point3i npoint = cpatches[i];
    std::vector<cv::Point3i> objects;
    std::cout << npoint << std::endl;
    if (npoint.x != 1 && npoint.y != 1 && npoint.z != 1) {
        objects.push_back(npoint);
    } else {
        std::sort(objects.begin(), objects.end(), compare_row);
        int r1, r2, c1, c2;
        r2 = objects.front().y;
        r1 = objects.back().y;
        std::sort(objects.begin(), objects.end(), compare_col);
        c2 = objects.front().y;
        c1 = objects.back().y;
        cv::rectangle(display_obstacles, cv::Point(r1, c1), cv::Point(r2, c2), CV_RGB(0, 255, 0));
        std::cout << "hhh" << r1 << ", " << c1 << "; " << r2 << ", " << c2 << "; ";
        objects.clear();
    }
}

你能帮我确定调用向量的第一个和最后一个元素时犯了什么错误吗?

【问题讨论】:

  • npointx,y,z 中有1 时,objects 中没有对象。
  • 如果cpatches 中的第一个npoint 要去else 分支怎么办? objects 将是空的,在 objects.front() 你会得到段错误。

标签: c++ vector segmentation-fault


【解决方案1】:

如果vector 实例为空,那么对于我们来说,它的front()back() 方法都是未定义的行为(这两种方法都假定至少存在一个元素)。这几乎可以肯定是导致您的问题的原因。

在这种情况下,在将任何元素推送到 objects 之前,点击您的 else 子句。防止这种情况的一种简单方法是更改​​线路:

} else {

} else if (!objects.empty()) {

【讨论】:

  • 但是为什么对象向量变成空的?甚至使用 objects.push_back(npoint); 添加元素,向量是空的?你能解释一下吗?
  • 好的,我明白了,std::vector<:point3i> 对象;应该在 for 循环之外定义。否则它总是会创建一个新的向量实例,这使它成为任何 i 的空向量。
猜你喜欢
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多