STL中,reserve()方法和resize()方法的区别,这是一个老生常谈的问题了
下面以容器vector为例,讲清楚二者区别:
size 和 capaticy
首先我们来了解vector的两个概念: size和capacity
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之间的元素,只能通过insert和push_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至少为n;resize(n)保证容器容纳的元素个数为n -
reserve()只是对capacity做出改变;而resize()既会改变size,也有可能改变capacity(当n > capacity) -
当
n < capacity的时候,reserve()不会做任何处理;而resize会删除元素,保证容器容纳的元素个数为****n -
reserve()只会分配空间,并不会插入数据,因此新空间仍是未初始化的,无法通过下标访问;resize()在分配空间的同时,会插入新数据,可以通过下标访问new_size - capacity之间的空间 -
reserve()的主要用途是预分配内存,避免频繁的内存重分配,提高性能 -
resize()则是直接改变容器中有效元素的数量,会实际创建或销毁元素

267

被折叠的 条评论
为什么被折叠?



