笔记(二)——vector容器基础理论知识

vector容器优点:

  1. 可以随机存取元素。

  1. 可以在尾部高效添加和移除元素。

一、vector容器的对象构造方法

vector采用模板类实现默认构造

例如vector vecT;

#include
#include
using namespace std;
int main()
{
    int arr[]={0,1,2,3,4};
    vector vecInt;       //建立一个存放int的vector容器 
    vector vecFloat;   //建立一个存放float的vector容器  
    vector vecString; //建立一个存放string的vector容器

    return 0;
} 

vector对象的带参数构造

  1. vector vecT(beg,end);该构造函数将区间[beg,end)中的元素拷贝给本身vecT。

beg,end是数组元素的地址。

#include
#include
using namespace std;
int main()
{
    int arr[]={0,1,2,3,4};
//    vector vecInt;       //建立一个存放int的vector容器 
//    vector vecFloat;   //建立一个存放float的vector容器  
//    vector vecString; //建立一个存放string的vector容器

//1、vector对象带参数构造 
//正确写法 
    vector vecInt1(arr,arr+5);                              //建立一个存放int的vector容器,初始为0,1,2,3,4 
    vector vecInt2(vecInt1.begin(),vecInt1.end());           //建立一个存放int的vector容器,初始为0,1,2,3,4 
    vector vecInt3(vecInt1.begin(),vecInt1.begin()+5);       //建立一个存放int的vector容器,初始为0,1,2,3,4 
    vector vecInt4(vecInt1.end()-5,vecInt1.end());           //建立一个存放int的vector容器,初始为0,1,2,3,4  
   
//错误写法 
//    vector vecInt; 
//    vecInt(arr,arr+5); 
//    vecInt2(arr.begin(),arr.end());

    return 0;
} 
  1. vector vecT(n,elem);该构造函数将n个elem拷贝给本身vecT。

    你可能感兴趣的:(C++STL学习笔记,c++,STL,C)