访问类中向量的特定索引时崩溃



我目前正在尝试制作一个表示像素的二维矢量。问题是,当我试图在特定索引处设置一个值时,程序会崩溃。汇编得很好。这是.h:

#include "../include/graphics.h"
#include <stdlib.h>
#include <stdio.h>
#include <functional>
#include <vector>
#include <string>
using namespace rgb_matrix;
class Viewport
{
public:
Viewport(std::string id,int xMn,int yMn,int xMx,int yMx,Canvas *c)
{
canvas_=c;
_id = id;
_x = xMn;
_y = yMn;
width=xMx-xMn;
height=yMx-yMn;
}
void SetPixel(int x_vport,int y_vport,rgb_matrix::Color c);
int getXMax(){
return _x + height;
}
int getHeight(){
return height;
}
int getWidth(){
return width;
}
int getX(){
return _x;
}
void clear();
std::string getId(){return _id;}
void show();
void fill(int r,int g,int b);
private :
Canvas *canvas_;
int width,height;
int _x,_y;
std::string _id;
std::vector<std::vector<rgb_matrix::Color> > colors;
};

奇怪的是,我可以访问.h中的值,但不能访问.cpp:

void Viewport::SetPixel(int x, int y, rgb_matrix::Color c) {
if(x>=0 && y>= 0 && x< width && y < height) {//if in rectangle
colors.at(x).at(y) = c;
}
}

这是而不是如何在向量中填充值:

void Viewport::SetPixel(int x, int y, rgb_matrix::Color c) {
if(x>=0 && y>= 0 && x< width && y < height) {//if in rectangle
colors.at(x).at(y) = c;
}
}

在访问向量colors.at(x)的元素之前,必须确保向量colors.size()的大小大于x。所以,在用值填充向量之前,可能在其他地方调用colors.resize()

崩溃是预期的,这是由于越界访问而引发的异常。

我会质疑数据结构的选择:

  • std::vector<rgb_matrix::颜色>如果您需要连续内存块,可以选择(只需记住调整其大小或使用width*height参数=构建(
  • 向量的向量意味着一个密集的非矩形结构——通常它用于三角形矩阵之类的东西来节省内存
  • CCD_ 5可以用于在随机位置具有几个像素的稀疏结构

如果切换到unsigned而不是int=(,也可以避免x>=0 && y>= 0