C++之vector容器操作演示

最简单的STL容器是vector容器,它在数据结构上与数组相似,占据着一个连续的内存块,但要比数组要灵活,是一个能够动态改变自身大小的数组。

#include<iostream> 
#include<vector>
#include<algorithm>
#include<functional>    // greater<T>
using namespace std;

template<class T>
void printVector(const char *s, const vector<T>& v) 
{
    cout<<s<<"=(";
    if(v.size()==0){
        cout<<")\n";
        return;
    }
    typename vector<T>::const_iterator i=v.begin();
    for( ;i<v.begin()+v.size()-1;i++)
        cout<<*i<<' ';
    cout<<*i<<")\n";
}
bool f1(int n) 
{
    return n<4;
}

int main()
{
    int a[]={1,2,3,4,5};
    vector<int> v1;             //v1 is empty,size=0,capacity=0
    for(int j=1; j<=5; j++)
        v1.push_back(j);        //v1=(1 2 3 4 5),size=5,capacity=8 
    printVector("v1",v1);
    vector<int> v2(3,7);        //v2=(7 7 7) 
    printVector("v2",v2);
    vector<int>::iterator i1=v1.begin()+1;
    vector<int>v3(i1,i1+2);     //v3=(2 3),size=2,capacity=2
    printVector("v3",v3);
    vector<int> v4(v1);         //v4=(1 2 3 4 5),size=5,capacity=5
    printVector("v4",v4);
    vector<int> v5(5);          //v5=(0 0 0 0 0)
    printVector("v5",v5);
    v5[1]=v5.at(3)=9;           //v5=(0 9 0 9 0)
    printVector("v5",v5);
    v3.reserve(6);              //v3=(2,3),size=2,capacity=6
    v4.resize(7);               //v4=(1 2 3 4 5 0 0),size=7,capacity=10
    v4.resize(3);               //v4=(1 2 3),size=3,capacity=10
    v4.clear();                 //v4 is empty,size=0,capacity=10(!)
    v4.insert(v4.end(),v3[1]);                  //v4=(3)
    v4.insert(v4.end(),v3.at(1));               //v4=(3 3)
    v4.insert(v4.end(),2,4);                    //v4=(3 3 4 4)
    v4.insert(v4.end(),v1.begin()+1,v1.end()-1);//v4=(3 3 4 4 2 3 4)
    v4.erase(v4.end()-2);                       //v4=(3 3 4 4 2 4)
    v4.erase(v4.begin(),v4.begin()+4);          //v4=(2 4)
    v4.assign(3,8);                             //v4=(8 8 8)
    v4.assign(a,a+3);                           //v4=(1 2 3)
    printVector("v4",v4);
    vector<int>::reverse_iterator i3=v4.rbegin();
    for( ;i3!=v4.rend();i3++)
        cout<<*i3<<' ';         //print:3 2 1
    cout<<endl;

    //algorithms
    v5[0]=3;                                    //v5=(3 9 0 9 0)
    replace_if(v5.begin(),v5.end(),f1,7);       //v5=(7 9 7 9 7)
    v5[0]=3;v5[2]=v5[4]=0;                      //v5=(3 9 0 9 0)
    replace(v5.begin(),v5.end(),0,7);           //v5=(3 9 7 9 7)
    sort(v5.begin(),v5.end());                  //v5=(3 7 7 9 9)
    sort(v5.begin(),v5.end(),greater<int>());   //v5=(9 9 7 7 3)
    v5.front()=2;                               //v5=(2 9 7 7 3)
    printVector("v5",v5);
    return 0;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值