将数组的大小放大两倍的c++方法
c++ way to enlarge size of array by two?
这是我当前的代码。在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;
}
相关文章:
- 重复使用预分配的向量<复杂<double>>作为<double>长度两倍的向量
- 计算C++两倍的差值
- 为什么当我进入退出条件时,程序会打印两倍的默认条件而不是退出 while 循环?
- 内存移动的性能与memcpy相比是两倍?
- Qt 是 JSON 精度的两倍
- 不完整的多线程光线追踪器花费的时间是预期的两倍
- C++随机函数给出的相同整数是输出的两倍
- 为什么我的最终向量是它应该大小的两倍并且具有前导 0?
- 为什么即使在从int到两倍的类型施放后,小数也没有小数
- 如何将固定精度的两倍格式化为给定的长度
- getsockopt() 返回的值是之前由 setsockopt() 设置的值的两倍
- MF SinkWriter mp4文件的播放持续时间是添加音频样本时的一半,图像的播放速度也是添加音频样本的两倍
- 无论如何,是否可以使用setCursorPos(int,int)函数,但没有采用两个int使它需要速度较慢的两倍
- 是一个包含两个INT(只有两个INT)的结构,保证是大小(INT)的两倍
- C++ "time.h"测量的运行时间是实际值的两倍
- 退出申请致电两倍
- SSE42 & STTNI - PcmpEstrM比PcmpIstrM慢两倍,是真的吗?
- 在同一台机器上,是否保证两倍值的不精确性是一致的
- 处理数据的方法,速度是我处理速度的两倍
- C++11 getline 要求输入的两倍