如何在运行时在对象数组中动态追加新对象C++并打印它们

How to dynamically append new object at run time in C++ array of object and print them

本文关键字:对象 C++ 打印 追加 运行时 数组 动态 新对象      更新时间:2023-10-16

我有一个类点。

我有一个事件调用点更改。这可能会发生任意次数。在每个事件中,事件都会给出一个新点。 所以我事先不知道如何提前分配积分。它可能只有 1 2 或数百个。

所以我想到了使用动态内存分配。 所以我创建了一个 Point 类型的指针 p。

我按点分配了一个参考存储器* p = (点*(malloc(sizeof(p((;

在主方法中插入第一个点 (0, 0(。 所有其他点都插入到 onPointChange 事件中。

现在,我希望在onPointChange事件中检测到的点附加到我的指针(p(中,并且还保留其所有先前的值。 最后打印出来。

#include <iostream>
#include <string>
#include <array>
using namespace std;
class point {
public:
int x;
int y;
};
point* p = (point*)malloc(sizeof(p));
int main()
{
p.x =0;
p.y =0;
// Now all other points to be filled in onPointChange event
}
void onPointChange(){
point newpoint;
newpoint.x = newXValue;
newpoint.y = newYValue;
// Here I need to reallocate my pointer p such that the new point (newpoint) is appended to the p and also all of its earlier elements are preserved.
// And after meeting any condition, print the value of x and y of all points in p
}

不能"追加"到指针。您可以根据需要使用std::vector来存储点,然后在满足条件时在矢量中打印点。