vector中的push_back()学习

std::vector::push_back

Addelement at the end

Addsa 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.

 

Thiseffectively increases the container size by one,which causes an automatic reallocation of the allocated storage space if -andonly if- the new vector size surpasses the current vector capacity.

 

因此每次執行的時候,都會在vector的尾部加入新的內容,並且val原來的內容也會拷貝進來。

這樣執行的好處是容量會自動加一,自動重新分配存儲空間。這樣避免了我們的新vector容量超出原來vector容量的情形發生。


#include<iostream>
#include<vector>

using namespace std;

int main(){
	vector<int>v1(10,1);
	size_t ix = 0;
	while (ix != v1.size())
		cout << v1[ix++] << endl;
	cout << "please input a number" << endl;
	int x;
	cin >> x;
	v1.push_back(x);
	cout <<"the new size of v1 is"<< v1.size() << " and the last element is " << v1[v1.size() - 1] << endl;
	cout << "input another number" << endl;
	cin >> x;
	v1.push_back(x);
	cout << "the new size of v1 is"<< v1.size() << " and the last element is " << v1[v1.size() - 1] << endl;
		return 0;
	
}
這個就是分配一個容量為10的數組v1,每次重新輸入一個新的數字時候,數組容量會自動加1,並且將新的元素加入到數組的尾部。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值