C++面试题——STL,reserve()和resize()的区别

STL中,reserve()方法和resize()方法的区别,这是一个老生常谈的问题了

下面以容器vector为例,讲清楚二者区别:

size 和 capaticy

首先我们来了解vector的两个概念: sizecapacity

  • size,表示vecctor已经容纳的元素个数
  • capacity,表示vector可以容纳的最大元素个数,即容量

reserve()

void reserve (size_type n);

Request a change in capacity

Requests that the vector capacity be at least enough to contain n elements.

If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).

In all other cases, the function call does not cause a reallocation and the vector capacity is not affected.

This function has no effect on the vector size and cannot alter its elements.

即:

  • reserve()只是对capacity做出改变

  • reserve(n),表示让容器至少能够容纳n个元素

    • 如果n > capacity,那么就会对容器进行扩容,直到capacity >= n
    • 否则,该函数调用不会做任何处理(既不会缩容,也不会改变capacity
  • reserve()不会影响size,同时无法直接通过下标访问size ~ capacity之间的元素,只能通过insertpush_back插入元素。即reserve不会创建元素对象


resize()

void resize (size_type n, value_type val = value_type());

Change size

Resizes the container so that it contains n elements.

If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.

If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.

Notice that this function changes the actual content of the container by inserting or erasing elements from it.

即:

  • 改变size属性,使得容器容纳n个元素

    • 如果n< old_size,那么容器只会保留前new_size个元素,并移除、销毁后面的元素。但不会减小capacity
    • 如果capacity >= n > old_size,那么就会向容器中插入新元素,直到content.size() == n。同样不会减小capacity
    • 如果n > capacity,那么首先会将capacity >= new_size,并对容器扩容,同时插入新元素,直到content.size() == n
  • resize()方法,会通过新增或删除数据的方式来改变容器存储的内容,并且当 n > capacity的时候,回对容器扩容,并修改capacity


总结

  • reserve(n)保证capacity至少为nresize(n)保证容器容纳的元素个数为n

  • reserve()只是对capacity做出改变;而resize()既会改变size,也有可能改变capacity(当 n > capacity

  • n < capacity的时候,reserve()不会做任何处理;而resize会删除元素,保证容器容纳的元素个数为****n

  • reserve()只会分配空间,并不会插入数据,因此新空间仍是未初始化的,无法通过下标访问;resize()分配空间的同时,会插入新数据,可以通过下标访问new_size - capacity之间的空间

  • reserve()的主要用途是预分配内存,避免频繁的内存重分配,提高性能

  • resize()则是直接改变容器中有效元素的数量,会实际创建或销毁元素

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Forward♞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值