欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++ vector ------- push_back(elem), push_back()

程序员文章站 2022-03-22 20:50:10
...


#include <string.h>
#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<double>v1;	//创建一个向量存储容器 double
    vector<double>v2;	//创建一个向量存储容器

    cout<<"v1: ";
    for(int i=0;i<10;i++) // push_back(elem)在数组最后添加数据elem
    {
        v1.push_back(i);
        cout<<v1[i]<<",";
    }

    cout<<endl<<"v2: ";
    for(int i=0;i<10;i++) // push_back(elem)在数组最后添加数据elem
    {
        v2.push_back(i);
        cout<<v2[i]<<",";
    }

    double arr[10];
    cout<<endl<<"arr=v1+v2: ";
    for(int i=0;i<10;i++)
    {
        arr[i] = v1[i] + v2[i];
        cout<<arr[i]<<",";
    }


    /////////////////////////////////////////////////
    for(int i=0;i<5;i++)//pop_back()去掉数组最后一个数据
    {
        v1.pop_back();
    }

    cout<<"\nAfter pop: ";

    for(int i=0;i<v1.size();i++)//size()容器中实际数据个数
    {
        cout<<v1[i]<<",";
    }


    return 0;
}


运行结果:

v1: 0,1,2,3,4,5,6,7,8,9,
v2: 0,1,2,3,4,5,6,7,8,9,
arr=v1+v2: 0,2,4,6,8,10,12,14,16,18,
After pop: 0,1,2,3,4,