POINT的C ++向量

时间:2017-09-04 19:44:50

标签: c++ vector

在我的程序中,我试图将当前鼠标位置设置为某个点,然后使用这些点填充数组。这是一个小例子,我只设置向量的第0个索引。

我遇到pointList[0].x = p.x行后会收到此错误;

  

将无效参数传递给认为无效参数致命的函数。

vector<POINT> pointList;
POINT p;
int i = 0;

while (!GetAsyncKeyState(VK_ESCAPE)) {

    system("PAUSE");
    GetCursorPos(&p);  // When key is pressed unpauses and gets position

    pointList[i].x = p.x;
    pointList[i].y = p.y;

    i++;
}

感谢任何帮助。我觉得向量被声明但是没有初始化是一个问题吗?

1 个答案:

答案 0 :(得分:1)

如果要使用operator[]访问向量,则需要声明并初始化向量的大小。

例如 -

std::vector<int> myvector (10);   // 10 zero-initialized elements
myvector[0] = 0;                  //this is valid

否则,如果您想要动态分配,请使用{ - 3}} -

vector<POINT> pointList;
POINT p;
int i = 0; //not required

while (!GetAsyncKeyState(VK_ESCAPE)) {

  system("PAUSE");
  GetCursorPos(&p);  // When key is pressed unpauses and gets position

  pointList.push_back(p);  //entire <POINT> 'p' is inserted into end of the vector.

  i++; //not required
}
相关问题