C++ reserve 与 resize的区别


 

resize要求容器具有sz个元素,可以使用c类型拷贝填充。否则用默认构造子填充;调用resize之后,容器的size()返回值发生改变;

reserve要求容器可以容纳至少N个元素。它实际是要求容器分配内存,但容器中本身没有元素,换言之,size()返回值不改变;


 

vector::resize

public member function

void resize ( size_type sz, T c = T() );

Change size

Resizes the vector to contain sz elements.
If sz is smaller than the current vector size, the content is reduced to its first sz elements, the rest being dropped.
If sz is greater than the current vector size, the content is expanded by inserting at the end as many copies of c as needed to reach a size of sz elements. This may cause a reallocation.
Notice that this function changes the actual content of the vector by inserting or erasing elements from the vector; It does not only change its storage capacity. To direct a change only in storage capacity, use vector::reserve instead.

Parameters
sz
New vector size, expressed in elements.
Member type size_type is an unsigned integral type.
c
Object whose content is copied to the added elements in case that  sz is greater than the current vector  size.
If not specified, the default constructor is used.
T is the first template parameter (the type of the elements stored in the vector).
Return Value
none
If a reallocation happens, it is performed using Allocator::allocate() , which may throw exceptions (for the default allocator bad_alloc  is thrown if the allocation request does not succeed).
Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

// resizing vector
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;

  unsigned int i;

  // set some initial content:
  for (i=1;i<10;i++) myvector.push_back(i);

  myvector.resize(5);
  myvector.resize(8,100);
  myvector.resize(12);

  cout << "myvector contains:";
  for (i=0;i<myvector.size();i++)
    cout << " " << myvector[i];

  cout << endl;

  return 0;
}

The code sets a sequence of 9 numbers as an initial content for myvector. It then uses resize first to trim the vector to a size of 5, then to extend its size to 8 with values of 100 for its new elements, and finally it extends its size to 12 with their default values (for int elements this is zero). Output:

myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0

vector::reserve

public member function

void reserve ( size_type n );

Request a change in capacity

Requests that the capacity of the allocated storage space for the elements of the vector container be at least enough to hold n elements.
This informs the vector of a planned increase in size, although notice that the parameter n informs of a minimum, so the resulting capacity may be any capacity equal or larger than this.
When n is greater than the current capacity, a reallocation is attempted during the call to this function. If successful, it grants that no further automatic reallocations will happen because of a call to vector::insert or vector::push_back until the vector size surpasses at least n (this preserves the validity of iterators on all these future calls).
A reallocation invalidates all previously obtained iterators, references and pointers to elements of the vector.
In any case, a call to this function never affects the elements contained in the vector, nor the vector size (for that purposes, see vector::resize or vector::erase, which modify the vector size and content).

Parameters
n
Minimum amount desired as capacity of allocated storage.
Member type size_type is an unsigned integral type.
Return Value
none
If the requested size to allocate is greater than the maximum size ( vector::max_size ) a length_error  exception is thrown.
In case of reallocation, this is performed using Allocator::allocate() , which may throw its own exceptions (for the default allocator bad_alloc  is thrown if the allocation request does not succeed).
Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

// vector::reserve
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> content;
  size_t filesize;

  ifstream file ("test.bin",ios::in|ios::ate|ios::binary);
  if (file.is_open())
  {
    filesize=file.tellg();

    content.reserve(filesize);

    file.seekg(0);
    while (!file.eof())
    {
      content.push_back( file.get() );
    }

    // print out content:
    vector<int>::iterator it;
    for (it=content.begin() ; it<content.end() ; it++)
      cout << hex << *it;
  }

  return 0;
}

This example reserves enough capacity in a vector of ints to store the content of an entire file, which is then read character by character (each character stored as an element in the vector). By reserving a capacity for the vector of at least the size of the entire file, we avoid all the automatic reallocations that the object content could suffer each time that a new element surpassed the size of its previously allocated storage space.


本文转自海天一鸥博客园博客,原文链接:http://www.cnblogs.com/sgsoft/archive/2011/04/28/2031910.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值