新似乎没有办法增加或减少分配?
new doesn't seem to have a way to grow or shrink allocations?
我在x轴上有n个点。在程序开始时,我用npoints
分配x。例如x = new double[npoints];
在模拟期间,CCD_ 3可以变化。如果npoints
增加,我想增加分配的内存。此外,如果npoints
减少,我想删除减少的内存。
使用::std::vector
。
#include <vector>
void foo()
{
::std::vector<double> x;
x.resize(5);
x[4] = 2.0;
x.resize(2);
// etc...
}
您提到的用例正是::std::vector
产生的原因。
现在,如果将向量的大小调整得更小,它通常不会释放内存。这有很多原因,shrink_to_fit
上的StackOverflow问题描述了为什么:shrink_to_fit是将容量"std::vector"减小到其大小的正确方法吗?
但是,如果您真的想向实现提示应该取消分配额外的点,请执行以下操作:
#include <vector>
void foo()
{
::std::vector<double> x;
x.resize(5);
x.shrink_to_fit(); // It didn't get smaller here, but I'm guessing you may
x[4] = 2.0; // not know that when you resize the vector in your own code.
x.resize(2);
x.shrink_to_fit();
// etc...
}
矢量仍然可能不会实际缩小分配。如果这真的是一个问题,那么这是一个需要在实现中解决的问题。
如果是的问题,并且您必须缩减分配,并且无法修复实现,那么您可以这样做:
#include <iterator>
#include <algorithm>
#include <utility>
#include <vector>
template <class T>
void shrinkwrap_vector(::std::vector<T> &x)
{
using namespace ::std;
typedef vector<T> vec_t;
const auto old_cap = x.capacity();
x.shrink_to_fit(); // Try shrink_to_fit first to see if it works.
if ((x.capacity() == old_cap) && (old_cap > x.size())) {
vec_t t;
t.reserve(x.size());
move(x.begin(), x.end(), back_inserter(t));
swap(x, t);
}
}
然后打电话给
shrinkwrap_vector(x);
而不是x.shrink_to_fit()
。这只需要将您的向量复制到一个全新的向量中,该向量的大小与您的实现所允许的大小一样接近。
还要注意,如果您存储的东西有一个非平凡的析构函数(double有一个平凡的析构函数),那么在执行resize
时,将为每个丢弃的元素调用该析构函数。整个shrink_to_fit
只是关于内存分配,而不是关于构建或销毁。
最后,如果您真的、真的想使用malloc
和realloc
调用,那么您可以创建一个使用这些调用的自定义vector
类。不过,除非您将自定义类指定为double
,否则您必须格外小心。您必须对分配内存后添加的任何元素调用构造函数,并在释放内存之前对任何丢弃的元素调用析构函数。
写这类课很复杂。您需要符合对C++中容器类的期望,以使它能够顺利地与其他一切一起工作。这包括生成迭代器类和类似性质的东西。
- 将数组的地址分配给变量并删除
- 数组索引的值没有增加
- vector.resize()中的分配错误
- 如何增加以前由新运算符分配的 C++ std::list 数组的大小?
- 如何在C++中为增加但记住删除先前对象的对象分配唯一标识符
- Linux getrusage()maxrss最大驻留集大小不随分配而增加(C++)
- 当必须将其尺寸增加时,请避免重新分配其尺寸
- 特征库,简单的线性代数操作,具有稀疏的矩阵,增加了其分配的尺寸
- 如何重新分配和增加字符串变量的值
- 新似乎没有办法增加或减少分配?
- 如何分配结构,然后增加其大小
- 我可以告诉VC2010自动增加预编译头分配(与/Zm相同),而不是获得c3859吗
- 为什么将地图的元素设置为其大小会在分配之前增加大小*
- STL矢量:当矢量容量因插入而增加时,在分配新的连续内存后,是否删除或保留旧的连续内存
- 分而治之真的能战胜增加的内存分配吗
- managed_mapped_file是否能够由于分配而增加文件大小
- 尝试使用while循环取消分配向量,任务管理器显示内存使用正在增加
- 动态内存分配会增加运行时间吗?
- 访问地图元素会增加其分配的内存大小
- 防止gcc中的std::函数分配内存或增加阈值