Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2039550
  • 博文数量: 414
  • 博客积分: 10312
  • 博客等级: 上将
  • 技术积分: 4921
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-31 01:49
文章分类

全部博文(414)

文章存档

2011年(1)

2010年(29)

2009年(82)

2008年(301)

2007年(1)

分类: C/C++

2009-01-04 14:36:05

void reserve ( size_type n );

Request a change in capacity

Requests that the of the allocated storage space for the elements of the container be at least enough to hold n elements.

This informs the of a planned increase in , 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 , 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 or until the vector 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 (for that purposes, see or , which modify the vector 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 () 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

// vector::reserve
#include 
#include 
#include 
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() ; itreturn 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 for the 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.

Complexity

Linear at most.

See also

Return size of allocated storage (public member function)
Resize string (public member function)
Return maximum size of string (public member function)
阅读(1613) | 评论(0) | 转发(0) |
0

上一篇:vector

下一篇:string

给主人留下些什么吧!~~