2

有什么区别:

std::vector::erase

std::vector::clear

我想要做的是摆脱所有元素,位置,包括内存地址并且没有抛出异常。

vector<array<double,1000>> S1(1000);

最后我想摆脱 1000*2 创建的内存地址。

4

5 回答 5

4

erase gets rid of elements selectively by position. clear gets rid of all elements unconditionally, and can be considered syntactic sugar for a call to v.erase(v.begin(),v.end());

于 2013-06-24T08:30:31.473 回答
2

The only sure way to release the memory that I can think of is to swap with a temporary vector:

vector<array<double,1000>> S1(1000);
...
vector<array<double,1000>>().swap(S1);

Although this might look strange at first, it is a known, widely used idiom.

In C++11, moving from the original vector might be an option, although it is not guaranteed to clear the memory or even clear the vector (I cannot think of a reason why an implementation wouldn't do that though):

{
  vector<array<double,1000>> tmp(std::move(S1));
} // tmp dies on exiting scope, memory is cleared

Altenratively, a call to std::vector::shrink_to_fit could result in memory de-allocation, but there are no guarantees:

S1.clear();
S1.shrink_to_fit();
于 2013-06-24T08:43:26.313 回答
0

擦除可让您指定开始和结束位置,而清除则清除整个向量。

http://www.cplusplus.com/reference/vector/vector/erase/

http://www.cplusplus.com/reference/vector/vector/clear/

于 2013-06-24T08:31:39.033 回答
0

v.erase(v.begin(),v.end()) 等价于 v.clear() 其中 v 是任何向量的对象。这里 clear 将用于删除所有向量元素,但 erase 可以用来删除任何特定元素或元素范围。

于 2014-01-05T14:35:11.770 回答
0

该函数clear()清空向量。该函数erase()删除选择性元素(有几个重载)。erase(v.begin(), v.end());相当于调用clear();. 创建的内存仍将保留以备将来使用。如果你想确保释放所有这些内存,那么如果你有 C++11 编译器,请调用v.clear();and then 。v.shrink_to_fit()(实际上并不能保证内存会被释放,这只是一个请求,但我不知道有任何编译器不会释放内存。)如果您不符合 C++11,请使用替代方案std::vector<std::array<double,1000>>().swap(v);. 这被称为缩小以适应成语

于 2013-06-24T08:56:17.773 回答