一种在循环中创建结构的更好方法

san*_*dra 1 c++ struct pointers loops new-operator

我已经很久没用C++编写了代码.最近,我正在尝试处理涉及结构的事情.像这样

typedef struct{
    int x;
    int y;
} Point;
Run Code Online (Sandbox Code Playgroud)

然后在循环中,我正在尝试创建新的结构并在列表中将它们指向它们.

Point* p;
int i, j;
while (condition){
    // compute values for i and j with some function...
    p = new Point;
    p* = {i, j}; //initialize my struct.
    list.append(p); //append this pointer to my list. 
} 
Run Code Online (Sandbox Code Playgroud)

现在,我的问题是可以简化这个吗?我的意思是,指针变量*p在循环之外并且在循环内调用p = new Point.是不是有更好/更好的语法?

小智 11

当然:

Point * p  = new Point;
Run Code Online (Sandbox Code Playgroud)

你可能也应该给你的Point类一个构造函数:

struct Point {      // note no need for typedef
    int x;
    int y;
    Point( int ax, int ay ) : x( ax ), y( ay ) {}
};
Run Code Online (Sandbox Code Playgroud)

这样你就可以说:

Point * p  = new Point( i, j );
Run Code Online (Sandbox Code Playgroud)

您可能还希望使列表成为Point值的列表,而不是指针,在这种情况下,您可以避免使用new进行动态分配 - 在C++中尽可能避免使用.


Aka*_*ksh 5

struct可以有一个构造函数,如:

struct Point{
    Point(int ax, int ay):x(ax), y(ay){}
    int x;
    int y;
};
Run Code Online (Sandbox Code Playgroud)

然后该函数可能如下所示:

int i, j;
while (condition)
{
    list.append(new Point(i,j));
} 
Run Code Online (Sandbox Code Playgroud)