vector resize()函数重新分配地址

std::vector resize() 函数
void resize (size_type n, value_type val = value_type());

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.

改变容器的大小使他包含n个元素。

如果n小于当前容器大小,则内容减少到前n个元素,移除后面的元素。
如果n大于当前容器大小,则在后面插入一些元素至n个大小,如果val被定义,则插入val的复制,否则插入默认值0。
如果n大于当前容器的容量capacity,则自动进行内容重新分配。


使用resize时,
如果n大于capacity,则会重新分配地址空间;n小于capacity,则仍旧使用原先的空间

#include <iostream>
#include <vector>
using namespace std;

int main() {
	cout  << "test\n";
	std::vector<int> tt;
	tt.reserve(20);
	for (int i=0; i<10; ++i) {
	    tt[i] = i;
	}
	std::cout << "原始地址: " << &tt[0] << std::endl;
	tt.resize(15);
	std::cout << "resize后(n < capacity): " << &tt[0] << std::endl; 
	tt.resize(30);
	std::cout << "resize后(n > capacity): " << &tt[0] << std::endl;
	return 0;
}

结果:

原始地址: 0x1318e80
resize后(n < capacity): 0x1318e80
resize后(n > capacity): 0x1318ee0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值