c++ - 循环条件中的空 vector<Point> size() 会导致奇怪的行为

标签 c++ opencv

我有一些我不理解的奇怪行为,也许我只是遗漏了一些明显的东西。我希望有人能解释一下。

这是导致问题的一些代码:

#include <stdio.h>
#include <tchar.h>
#include <iostream>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace cv;
using namespace std;

// draw line from point to point along the point "list"
void drawLineSegments(Mat img, vector<Point> points, Scalar colour = Scalar(255,255,255)){
    for (int i = 0; i < (points.size()-1); i ++){
        line(img,points[i],points[i+1], colour);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    Mat testImg = Mat(100,100,CV_8U,0.0); // test black image, not important

    vector<Point> testPoints; // new vector

    drawLineSegments(testImg,testPoints); // try to draw it, expect function to do nothing because size should be 0

    return 0;
}

这个编译但是在运行时给出了一个错误“vector subscript out of range”,通过调试我可以看到这是因为 for 循环运行。为什么 for 循环会运行?这是我不明白的。

调用 testPoints.size() 似乎返回 0,如果我将绘制函数更改为:

// draw line from point to point along the point "list"
void drawLineSegments(Mat img, vector<Point> points, Scalar colour = Scalar(255,255,255)){
    int lengthMinusOne = points.size()-1;
    for (int i = 0; i < lengthMinusOne; i ++){
        line(img,points[i],points[i+1], colour);
    }
}

然后就可以了。那么为什么我不能在条件中直接使用 points.size() 呢?

最佳答案

这一行是罪魁祸首。

for (int i = 0; i < (points.size()-1); i ++){

具体来说,(points.size()-1)

这相当于说:

size_t s = points.size(); // Which is zero for you use case.
s = s - 1;  // This is not -1. It's large positive number.
for (int i = 0; i < s; i ++){

由于s != -1,你将在for循环中进入代码块,并从points访问成员,这导致未定义的行为。

关于c++ - 循环条件中的空 vector<Point> size() 会导致奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23433028/

相关文章:

c++ - Qt和opencv中的人脸检测

qt - 将 OpenCV 库链接到 Qt

c++ - 根据另一个图像访问和更改像素的颜色 - opencv c++

c++ - 打开文件对话框和内存泄漏

c++ - 如何在 C++ 中以结构体中的数组为目标

c++ - 从 .pcap 文件中获取 HID 报告描述符

Windows 7 中的 Javacv UnsatisfiedLinkError

c++ - 关于 C++ 中的 "bind"

c++ - C++ 中的 n 元组列表

OpenCV - 为视频生成自适应背景