c++ - 如何读取 Point vector 的 vector - C++

标签 c++ exception opencv vector

我有一个由 Point vector 组成的 vector (称为 squares,由 squares.cpp< 的 findSquares() 函数返回)/ (OpenCV)).

我想对存储在 Point vector 中的四个点的 x 和 y 坐标进行平均(用 c++ 语言)。

我试着这样做:

    vector <Point> coordinates(4);

    for ( int i = 0; i<squares.size();i++) {

        coordinates[0].x += squares[i][0].x;
        coordinates[0].y += squares[i][0].y;

        coordinates[1].x += squares[i][1].x;
        coordinates[1].y += squares[i][1].y;

        coordinates[2].x += squares[i][2].x;
        coordinates[2].y += squares[i][2].y;

        coordinates[3].x += squares[i][3].x;
        coordinates[3].y += squares[i][3].y;
    } 
    if(squares.size() !=0){
        for( int j=0; j<4; j++) {
            coordinates[j].x /= squares.size();
            coordinates[j].y /= squares.size();
        }
    }

但是我得到了这个异常:

enter image description here

我以错误的方式读取了 Point vector 的 vector 元素?

最佳答案

注意以下代码:

if (squares.size() !=0){
    for( int j=0; j<4; j++) {
        coordinates[j].x /= squares.size();
        coordinates[j].y /= squares.size();
    }
}

此代码块可能会在 coordinates[j].x 崩溃什么时候squares.size()大于 0 但小于 4。

想象一下 squares.size()是2。你认为它会在for中发生什么?当 j 时循环变成 2?该部门将成为 coordinates[2].x /= squares.size(); ,它试图访问 vector 中不存在的位置,从而导致崩溃。 记住:如果数组的大小为2,则 vector 的有效索引为0和1,因此2超出范围。

这是您的代码中的一个问题,可能是导致崩溃的原因。要修复它,请将循环更新为:

    for (int j = 0; j < squares.size(); j++) {

如果崩溃继续发生,则问题出在代码的其他地方。

关于c++ - 如何读取 Point vector 的 vector - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14677240/

相关文章:

python - 简单数字识别中的OpenCV Python错误

python - 如何修复 'cv2' 没有属性 'CascadeClassifier'?

c++ - 为什么在 C++ 中使用指针?

c++ - 在非 pod 结构上使用 operator new + Initializer list

创建hibernate配置时出现java.lang.ExceptionInInitializerError

java - 访问 FrameLayout 时出现运行时异常

python - 在 Windows 7 上为 Python 2.7 安装 OpenCV

python - 无法将长整数从嵌入式 Python 返回到 C++

c++ - 可以抛出具有私有(private)拷贝构造函数的对象吗?

python - 定义镜像内置异常格式的自定义 Python 异常