[英]Use a ::std::vector for array creation
我想在运行时增加一个 ::std::vector,就像这样:
::std::vector<int> i;
i.push_back(100);
i.push_back(10);
在某个时候,向量已完成,我不再需要 ::std::vector 提供的额外功能,因此我想将其转换为 C 数组:
int* v = i.data();
因为我会不止一次这样做,所以我想释放所有堆内存 ::std::vector 保留,但我想保留数据,就像这样(伪代码):
free(/*everything from ::std::vector but the list*/);
任何人都可以给我一些指示吗?
提前致谢,杰克
在我所看到的所有实现中,向量的分配部分是...数组本身。 如果您知道它不再增长,则可以尝试缩小它,以释放可能未使用的内存:
i.shrink_to_fit();
int* v = i.data();
当然,没有任何东西可以保证实现会做任何事情,但是唯一的安全选择是分配一个新数组,将数据从向量移到该数组并清除向量。
int *v = new int[i.size];
memcpy(v, i.data, i.size * sizeof(int));
i.clear();
但我真的怀疑您会通过这种方式获得重大收益...
您可以将std::vector
的内容用作C数组,而无需复制或释放任何内容。 只要确保std::vector
超过了使指针有效的需求(并且对向量本身进行了可能触发重新分配的进一步修改)即可。
当您通过data()
获得指向内部存储的指针时,您实际上并没有分配任何东西,只是引用已经分配的内存。
您可以用来节省内存的唯一其他预防措施是使用shrink_to_fit()
释放用作备用容量的任何多余内存(尽管不能保证)。
您有两种选择:
这是示例:
std::vector<int> vec;
// fill vector
std::unique_ptr<int[]> arr(new int[vec.size()]);
std::copy(vec.begin(), vec.end(), arr.get());
好的,感谢致力于此工作的每个人,我提出了以下解决方案:
auto v = new ::std::vector<int>();
// fill the vector
v->shrink_to_fit();
int* g = v->data();
free(v); // will free the memory the vector occupies, but not that of the array, since it does not call the destructor
如果我遇到了:: std :: vector比数组分配更多的实现,我将只执行#if并释放相应的地址。
感谢您的帮助,杰克
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.