惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
Martin Fowler
Martin Fowler
The GitHub Blog
The GitHub Blog
B
Blog RSS Feed
U
Unit 42
阮一峰的网络日志
阮一峰的网络日志
量子位
GbyAI
GbyAI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
L
LangChain Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园_首页
IT之家
IT之家
V
Visual Studio Blog
Y
Y Combinator Blog
Blog — PlanetScale
Blog — PlanetScale
宝玉的分享
宝玉的分享
Apple Machine Learning Research
Apple Machine Learning Research
I
InfoQ
D
Docker
V
V2EX

博客园 - 海天一鸥

Windows批处理中的等待技巧 The Ice::Current Object ICE代理的固有方法 C# Tips 2则 Configuring log4net with VS2010 and .Net 4.0 IoC Container Benchmark - Unity, Windsor, StructureMap and Spring.NET Functional .NET 4.0 – Tuples and Zip binary search of an integer array JAVA 上加密算法的实现用例 Exploring The Major Interfaces in Rx 带状疱疹覆灭记 ADO vs ADO.NET vs OLE DB vs ODBC [数据提供程序之间的差别] 获取SYSTEM账户的环境变量 如何在 Windows 7 中使用多线程加快文件复制? 关于VC++ 字符集 ICE bidirectional connections 关键点 你最后会划掉谁的名字…… Poco::DateTimeFormatter Tips POCO日志组件Tips
C++ reserve 与 resize的区别
海天一鸥 · 2011-04-28 · via 博客园 - 海天一鸥

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.