简体   繁体   中英

Vector subscript out of range error - C++ Vectors & Open CV

I am writing a program that would collect some coordinates and push them into a vector and finally send these vectors to a function that would create an image and plot the points present in these vectors.

My Program :

#include<opencv\cv.h>
#include<opencv\highgui.h>
#include<iostream>
#include<vector>
using namespace cv;
using namespace std;


void image_creator(vector<float>  jump_xx, vector<float>  jump_yy, vector<float>  mark_xx, vector<float>  mark_yy)
{

    Mat image_creator(Size(500, 500), CV_8UC3);

    for (int i = 0; i < sizeof(jump_xx); i++)
    {
        line(image_creator, Point(jump_xx[i], jump_yy[i]), Point(mark_xx[i], mark_yy[i]), Scalar(155, 122, 155), 4, 2, 0);
        waitKey(0);
    }
    namedWindow("Slice_Viewer1", CV_WINDOW_FREERATIO);
    imshow("Slice_Viewer1", image_creator);

}

int main()
{
    vector<float> jump_x;
    vector<float> jump_y;
    vector<float> mark_x;
    vector<float> mark_y;

    int x, y, a, b;
    int choice;

    jump_x.push_back(0.0);
    jump_y.push_back(0.0);

    mark_x.push_back(0.0);
    mark_y.push_back(10.0);

    jump_x.push_back(10.0);
    jump_y.push_back(0.0);

    mark_x.push_back(10.0);
    mark_y.push_back(10.0);

    image_creator(jump_x, jump_y, mark_x, mark_y);

    return 0;

}

The build is successful but when i run the code , i get this error:

在此处输入图片说明

sizeof will return size in bytes of the object representation of the type , which has nothing to do with the current object, and it's static and fixed. It doesn't return the number of elements, and you might get a out of bound error.

You should use std::vector::size() .

Change

for (int i = 0; i < sizeof(jump_xx); i++)

to

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

BTW: I suggest you to change the parameter from passing by value to passing by const reference, to avoid copying.

void image_creator(const vector<float>& jump_xx, const vector<float>& jump_yy, const vector<float>& mark_xx, const vector<float>& mark_yy)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM