c++ - 使用 std::vector 编写可调整大小的 vector 时出现问题

标签 c++

我是一名巴西 C++ 编码初学者(请原谅我对这两方面的知识匮乏)。我正在尝试编写一个 .txt 输出文件,其中包含我用鼠标单击的像素位置。我正在使用 opencv 库,所以这是代码的功能部分:

#include "opencv2/highgui/highgui.hpp"
#include <iostream>    
#include <vector> 
#include <fstream>    
using namespace std;
using namespace cv;

//declaration of vector and counter
int i = 1;
std::vector<int>vet_x(i);
std::vector<int>vet_y(i);


//the callback function
void CallBackFunc(int event, int x, int y, int flags, void* userdata)
{
    if (event == EVENT_LBUTTONDOWN)
    {

        vet_x.resize(i);
        vet_y.resize(i);

        vet_x[i] = x;
        vet_y[i] = y;
        i++;

        cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
    }
}

int main(int argc, char** argv)
{

    Mat img = imread("lena.jpg");
    //Create a window
    namedWindow("Mouse Track Test", 1);
    //set the callback function for mouse event
    setMouseCallback("Mouse Track Test", CallBackFunc, NULL);
    //show the image
    imshow("Mouse Track Test", img);
    // Wait until user press some key
    waitKey(0);

    //the writing begins after the press of the key
    ofstream myfile;
    myfile.open("points.txt");

    for (int j = 1; j <= vet_x.size(); j++)
    {
        cout << vet_x[j] << "," << vet_y[j] << endl;
        myfile << vet_x[j] << "," << vet_y[j] << endl;
    }
    myfile.close();

    return 0;
}

问题是:文件只写入最后点击的位置! 但如果我转动“vet_x.reserve(1024);”线,效果很好,但仅适用于 y 坐标...

那么,我的错误是什么?

最佳答案

C++ 数组索引是从 0 开始的。因此,当您将 vector v 的大小调整为大小 1 并分配给 v[1] 时,您将分配给一个不存在的项目。这是未定义的行为。

要捕获这种越界索引,您可以使用 at 方法,该方法保证会出现异常。即,编写 v.at(i) 而不是 v[i]

但是,您应该简单地使用 push_back 成员函数将项目添加到 vector 中。即 v.push_back( x ),其中 x 是您要添加的值。使用单个 2D 点 vector ,而不是一个 x vector 和一个 y vector 也是一个好主意。

关于c++ - 使用 std::vector 编写可调整大小的 vector 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28858141/

相关文章:

c++如何删除二维 vector 中的任何空元素

c++ - VS 6.0 C++ 执行 CL.EXE 导致“驱动器中没有磁盘.. <corrupt drive name>

c++ - 尝试将 C++ 绑定(bind)到 Haskell : getting undefined reference errors

c++ - 一段时间内声明中的奇怪行为 C++

c++ - 是否有可能继承自专门针对自己的模板类 C++

c++ - 在循环 C 中使用 libcurl

c++ - 带数组的嵌套结构

c++ - 通过函数c++填充指针数组

c++ - 计算一点到另一点的距离

C++:字段的类型不完整