STLvector中的shrink_to_fit方法(32)
原文地址:http://www.cplusplus.com/reference/vector/vector/shrink_to_fit/
public member function
std::vector::shrink_to_fit
void shrink_to_fit();
Shrink to fit
Requests the container to reduce its capacity to fit its size.
请求容器降低其容量和size匹配。
The request is non-binding, and the container implementation is free to optimize otherwise and leave the vector with a capacity greater than its size.
该请求不具有约束力,容器可以自由地去执行其他的优化方案(capacity可以大于size)。//我查了一下网上说是该方法由编译器决定是否真正释放多余的内存,该方法值是提出请求,是否要实现由编译器说了算。
例子:
// vector::shrink_to_fit
#include
#include
using namespace std;
int main ()
{
std::vector
std::cout << “1. capacity of myvector: “ << myvector.capacity() << ‘\n’;
cout<<”size=”<<myvector.size()<<endl;
myvector.resize(10);
std::cout << “2. capacity of myvector: “ << myvector.capacity() << ‘\n’;
cout<<”size=”<<myvector.size()<<endl;
myvector.shrink_to_fit();
std::cout << “3. capacity of myvector: “ << myvector.capacity() << ‘\n’;
cout<<”size=”<<myvector.size()<<endl;
return 0;
}
结果截图:
This may cause a reallocation, but has no effect on the vector size and cannot alter its elements.
这可能导致重分配,但不会影响其size以及不能改变其元素。
Parameters
none
Return value
none
Example
1 | 1 |
1 | // vector::shrink_to_fit |
Possible output:
1. capacity of myvector: 100
2. capacity of myvector: 100
3. capacity of myvector: 10
Complexity
At most, linear in container size.
与容器大小线性相关。
Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
如果发生重分配,所有的迭代器,指针以及引用都将失效。
Otherwise, no changes.
否则,不会改变其有效性。
Data races
The container is modified.
容器将被修改。
If a reallocation happens, all contained elements are modified.
如果发生重分配,所有容器内元素都将被修改。
Otherwise, no contained elements are accessed.
否则,元素不会被访问。
Exception safety
If the type of the elements is either copyable or no-throw moveable, there are no changes in the container in case of exception (strong guarantee).
如果元素的复制构造以及移动构造不会抛出异常,那么容器抛出异常的规则不变。
Otherwise, if an exception is thrown, the container is left with a valid state (basic guarantee).
否则,如果容器抛出异常,容器依旧承诺保持在有效状态。
//翻译的不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
2014-8-19
于GDUT
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/stlvector中的shrink-to-fit方法32/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!