现在的位置: 首页 > 综合 > 正文

vector中的push_back()学习

2018年04月16日 ⁄ 综合 ⁄ 共 919字 ⁄ 字号 评论关闭

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,並且將新的元素加入到數組的尾部。



抱歉!评论已关闭.