将数组的大小放大两倍的c++方法

c++ way to enlarge size of array by two?

本文关键字:两倍 c++ 方法 数组 放大      更新时间:2023-10-16

这是我当前的代码。在c++中是否有更好的方法来做同样的事情?

{
            // create more room in array
            Point *temp = new Point[pointList.getSize()*ENLARGE_TIMES];
            memcpy(temp,pointList._pointList,sizeof(Point)*pointList.getSize());
            pointList.~PointList();
            pointList._pointList = temp;
            pointList.setSize(pointList.getSize()*ENLARGE_TIMES);
            pointList._pointList[iterator] = point;
            iterator++;
            pointsCounter++;
            continue;
}

编辑:不能用一个向量

正如Chris指出的那样,您确实需要使用std::vector以及方法reserve()和push_back(),如下所示:

vector<Point> pointList; // could be a member variable
pointList.reserve(INITIAL_CAPACITY); // up to you
pointList.push_back(point); // adding new elem
pointList.end();  // replaces your iterator
// Some idiomatic iteration code to go with it:
for( auto iter = begin(pointList); iter != end(pointList); ++iter )
{
  Point p = *iter; // deref iterator and use result
}

如果你不想使用外部库,你可以为你的代码实现一个链表。尽管您可能需要重写程序的其他部分,但这是在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;
}