0

这是我当前的代码。有没有更好的方法在 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;
}

编辑:不能使用矢量

4

2 回答 2

1

正如 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
}
于 2013-04-29T00:10:38.927 回答
0

如果你想避免使用外部库,你可以为你的代码实现一个链表。尽管您可能必须重写程序的其他部分,但它是一种在 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;
}
于 2013-04-29T00:15:22.680 回答