如何在运行时在对象数组中动态追加新对象C++并打印它们
How to dynamically append new object at run time in C++ array of object and print them
我有一个类点。
我有一个事件调用点更改。这可能会发生任意次数。在每个事件中,事件都会给出一个新点。 所以我事先不知道如何提前分配积分。它可能只有 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
来存储点,然后在满足条件时在矢量中打印点。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象