vector中push_back后iterator失效程序崩溃的原因


vector的push_back操作

在c++ reference中,对push_back的描述如下:

void push_back(const value_type&val);
void push_back(value_type && val);

Add element at the end
Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.
This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

push_back的作用是在vector的末尾添加一个新元素。val的内容被复制(或移动)到新元素。
这有效地将容器大小增加一,当且仅当新的vector大小超过当前vector容量时,会重新自动分配新的存储空间。

在进行demo测试之前,再了解另外两个函数:
std::vector::size
vec.size() 返回vec中元素的个数

std::vector::capacity
vec.capacity() 返回vec在内存中分配的空间大小

Return size of allocated storage capacity
Returns the size of the storage space currently allocated for the vector, expressed in terms of elements.
This capacity is not necessarily equal to the vector size. It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.
Notice that this capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container (reallocating it storage space). The theoretical limit on the size of a vector is given by member max_size.
The capacity of a vector can be explicitly altered by calling member vector::reserve.


push_back操作的demo

//code1

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

#define MAX_NUM 9

int main(){
   
	vector<int> vecInt;
	
	for(int i = 0; i != MAX_NUM; i++){
   
		vecInt.push_back(i);
	}
	/**
		some code
	*/
	vecInt.push_back(123);

	for(int i : vecInt){
   
		cout << i << " ";
	}
	
	re
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值