STL vector中的shrink_to_fit方法(32)

coderguang發表於2014-08-19
public member function
<vector>

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 <iostream>
#include <vector>
using namespace std;
int main ()
{
  std::vector<int> myvector (100);
  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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// vector::shrink_to_fit
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (100);
  std::cout << "1. capacity of myvector: " << myvector.capacity() << '\n';

  myvector.resize(10);
  std::cout << "2. capacity of myvector: " << myvector.capacity() << '\n';

  myvector.shrink_to_fit();
  std::cout << "3. capacity of myvector: " << myvector.capacity() << '\n';

  return 0;
}


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






相關文章