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,如需转载请自行联系原作者

相关文章
|
存储 安全 C++
C++中的引用和指针:区别与应用
引用和指针在C++中都有其独特的优势和应用场景。引用更适合简洁、安全的代码,而指针提供了更大的灵活性和动态内存管理的能力。在实际编程中,根据需求选择适当的类型,能够编写出高效、可维护的代码。理解并正确使用这两种类型,是掌握C++编程的关键一步。
561 1
|
存储 C++ Cloud Native
云原生部署问题之C++ 中的 nullptr 和 NULL 区别如何解决
云原生部署问题之C++ 中的 nullptr 和 NULL 区别如何解决
321 0
|
算法 Java 数据库连接
Java 与 C++ 区别深入剖析及应用实例详解
本文深入剖析了Java和C++两种编程语言的区别,从编译与执行机制、面向对象特性、数据类型与变量、内存管理、异常处理等方面进行对比,并结合游戏开发、企业级应用开发、操作系统与嵌入式开发等实际场景分析其特点。Java以跨平台性强、自动内存管理著称,适合企业级应用;C++则因高性能和对硬件的直接访问能力,在游戏引擎和嵌入式系统中占据优势。开发者可根据项目需求选择合适语言,提升开发效率与软件质量。附面试资料链接:[点此获取](https://pan.quark.cn/s/4459235fee85)。
1163 0
|
存储 安全 编译器
在 C++中,引用和指针的区别
在C++中,引用和指针都是用于间接访问对象的工具,但它们有显著区别。引用是对象的别名,必须在定义时初始化且不可重新绑定;指针是一个变量,可以指向不同对象,也可为空。引用更安全,指针更灵活。
|
C语言 C++
C 语言的关键字 static 和 C++ 的关键字 static 有什么区别
在C语言中,`static`关键字主要用于变量声明,使得该变量的作用域被限制在其被声明的函数内部,且在整个程序运行期间保留其值。而在C++中,除了继承了C的特性外,`static`还可以用于类成员,使该成员被所有类实例共享,同时在类外进行初始化。这使得C++中的`static`具有更广泛的应用场景,不仅限于控制变量的作用域和生存期。
622 10
|
存储 编译器 C语言
C++内存管理(区别C语言)深度对比
C++内存管理(区别C语言)深度对比
514 5
|
Web App开发 Rust 分布式计算
Rust与C++的区别及使用问题之对于大量使用C++实现的产品来说,迁移到Rust的问题如何解决
Rust与C++的区别及使用问题之对于大量使用C++实现的产品来说,迁移到Rust的问题如何解决
424 1
|
Rust 安全 编译器
Rust与C++的区别及使用问题之Rust中的bound check对性能产生影响的问题如何解决
Rust与C++的区别及使用问题之Rust中的bound check对性能产生影响的问题如何解决
349 1
|
算法 Java C++
C++和Python在内存管理上的主要区别是什么?
【7月更文挑战第2天】C++和Python在内存管理上的主要区别是什么?
686 1