【发布时间】:2011-11-21 12:15:06
【问题描述】:
总之,我已经实现了一些功能,并且想问一些基本的事情,因为我对 C++ 没有扎实的基础知识。我希望,你们都好心地告诉我什么应该是我可以向你们学习的好方法。 (拜托,这不是作业,我身边没有任何专家来问这个问题)
我所做的是;我从一个文件中读取输入 x、y、z 点数据(大约 3GB 数据集),然后为每个点计算一个值并存储在一个向量中(结果)。然后,它将在下一个循环中使用。然后,该向量将不再使用,我需要获取该内存,因为它包含大量数据集。我想我可以通过两种方式做到这一点。 (1) 只需初始化一个向量,然后再将其擦除(参见代码 1)。 (2) 通过分配动态内存,然后再取消分配(参见代码 2)。我听说这种取消分配效率低下,因为取消分配会再次消耗内存,或者我可能误解了。
Q1) 我想知道在内存和效率方面的优化方式是什么。
Q2) 另外,我想知道按引用返回的函数是否是提供输出的好方法。 (请看code-3)
代码-1
int main(){
//read input data (my_data)
vector<double) result;
for (vector<Position3D>::iterator it=my_data.begin(); it!=my_data.end(); it++){
// do some stuff and calculate a "double" value (say value)
//using each point coordinate
result.push_back(value);
// do some other stuff
//loop over result and use each value for some other stuff
for (int i=0; i<result.size(); i++){
//do some stuff
}
//result will not be used anymore and thus erase data
result.clear()
代码-2
int main(){
//read input data
vector<double) *result = new vector<double>;
for (vector<Position3D>::iterator it=my_data.begin(); it!=my_data.end(); it++){
// do some stuff and calculate a "double" value (say value)
//using each point coordinate
result->push_back(value);
// do some other stuff
//loop over result and use each value for some other stuff
for (int i=0; i<result->size(); i++){
//do some stuff
}
//de-allocate memory
delete result;
result = 0;
}
code03
vector<Position3D>& vector<Position3D>::ReturnLabel(VoxelGrid grid, int segment) const
{
vector<Position3D> *points_at_grid_cutting = new vector<Position3D>;
vector<Position3D>::iterator point;
for (point=begin(); point!=end(); point++) {
//do some stuff
}
return (*points_at_grid_cutting);
}
【问题讨论】:
标签: c++