第三讲 vector

vector。支持尾部添加/删除数据操作。

// STL.cpp : 定义控制台应用程序的入口点。
//
//vector是一个连续的向量,相当于数组。vector不建议除了尾部之外的数据添加删除操作。
//vector<>::iterator 迭代器
#include "stdafx.h"
#include<iostream>
#include<vector>
using namespace std;

//void OutPut(vector<int> &oVector)
//{
//    vector<int>::const_iterator cit;
//    //for(int cit = oVector.cbegin(); cit != oVector.cend(); ++cit)
//    //{
//    //    cout << *cit << endl;
//    //}
//}

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> oInt;
    oInt.push_back(1);        //从后添加元素********************①
    oInt.push_back(2);
    oInt.push_back(3);
    oInt.push_back(4);

    for(int i = 0; i < oInt.size(); ++i)
    {
        cout << oInt[i] << endl;
    }

    cout << "push_back(5)之后:" << endl; 
    oInt.push_back(5);
    cout << "oInt容量:" << oInt.size() << endl;    //输出现有vector大小***************************②
    cout << "oInt分配容量:" << oInt.capacity() <<endl;    //输出现有vector分配容量大小********************③
    
    for(int i = 0; i < oInt.size(); ++i)
    {
        cout << oInt[i] << endl;
    }

    cout << "pop_back()之后:" << endl; 
    oInt.pop_back();    
    
    for(int i = 0; i < oInt.size(); ++i)
    {
        cout << oInt[i] << endl;
    }

        
    vector<int>::iterator it;        //定义一个可写迭代器
    cout<< "使用迭代器进行输出:" << endl;
    for(it = oInt.begin(); it != oInt.end(); ++it)
    {
        cout << *it << endl;
    }

    //1,2,3,4 ->
    //1,200,2,3,4
    cout << "插入之前的数据" <<endl;
    vector<int>::const_iterator cit;    //定义一个可读迭代器
    //插入数据
    for (cit = oInt.cbegin(); cit != oInt.cend(); ++cit)
    {
        if(*cit == 2)
        {
            oInt.insert(cit,200);    //插入数据*****************************④
            break;                    //一定要有
        }
    }

    cout << "插入之后的数据" <<endl;
    for (cit = oInt.cbegin(); cit != oInt.cend(); ++cit)
    {
        cout << *cit << endl;
    }

    //1,200,2,3,4->
    //1,2,3,4
    //删除数据
    for (cit = oInt.cbegin(); cit != oInt.cend(); ++cit)
    {
        if(*cit == 200)
        {
            oInt.erase(cit);        //删除数据***********************************⑤
            break;                    //一定要有
        }
    }
    cout<< "删除之后的数据" << endl;
    for (cit = oInt.cbegin(); cit != oInt.cend(); ++cit)
    {
        cout << *cit << endl;
    }
    return 0;
}

 

原文地址:https://www.cnblogs.com/zenseven/p/3806508.html