如果你想避免使用外部库,你可以为你的代码实现一个链表。尽管您可能必须重写程序的其他部分,但它是一种在 C++ 中处理动态增长内存的有效方法。我相信 std 库提供了用于创建这些结构的模板。如果您想自己实现它们,这里有一些片段可以帮助您入门:
结构:
struct PointNode {
int point;
PointNode * next;
};
添加数据:
void addPoint( PointNode ** head, int point ){
PointNode * temp = new PointNode;
temp->point = point;
temp->next = * head;
* head = temp;
}
释放内存:
void freeNodes( PointNode * head ){
PointNode * temp;
while( head ){
temp = head->next;
delete head;
head = temp;
}
}
当您需要将数据用作数组时:
int getPoints( PointNode * head, int ** points ){
PointNode * temp = head;
int i = 0;
for( ; temp; temp = temp->next, i++ );
( * points ) = new int[ i ];
for( i = 0, temp = head; temp; temp= temp->next, i++ ){
( * points )[ i ] = temp->point;
}
return i;
}
例子:
int main( ){
PointNode * head = 0; // make sure the head is always initialized to zero
addPoint( &head, 4 );
addPoint( &head, 5 );
addPoint( &head, -4 );
int * points;
int len = getPoints( head, &points );
for( int i = 0; i < len; i++ ) cout << points[ i ] << endl;
delete points;
freeNodes( head );
return 0;
}