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