STL中Vector的使用方法详解

转载自:http://blog.sina.com.cn/s/blog_5cf5e7c40100boiu.html

//VectorDemo.cpp : 定义控制台应用程序的入口点。
//Visual C++ 6.0 中编译通过

# include
# include

using namespace std;

typedef vector INTVECTOR;

void PrintIntVector(INTVECTOR iVector)
{
    //遍历vector方法
    cout<<"Vector: [";
    for(INTVECTOR::iterator it = iVector.begin(); it != iVector.end(); it++)
    {
        cout<<*it;
        if(it != iVector.end()-1)
        {
            cout<<",";
        }
    }
    cout<<"]"< }
int main(int argc, char* argv[])
{
    INTVECTOR iVector;
    //push_back方法
    iVector.push_back(2);
    iVector.push_back(3);
    iVector.push_back(4);
    iVector.push_back(1);
    iVector.push_back(10);
    iVector.push_back(20);
    PrintIntVector(iVector);
    //Vector: [2,3,4,1,10,20]
   
    //pop_back方法
    iVector.pop_back();
    PrintIntVector(iVector);
    //Vector: [2,3,4,1,10]
   
    //size、capacity 与 max_size方法
    cout<<"size="<     //First element:2
   
    //insert方法
    //PrintIntVector(iVector);
    iter = iVector.insert(iter, 65);
    iVector.insert(iter+1, 2, 30);
    iVector.insert(iVector.end(), iVector.begin(), iVector.end());//复制
    PrintIntVector(iVector);
    //Vector: [65,30,30,2,3,4,1,10,65,30,30,2,3,4,1,10]
   
    //at方法
    cout<<"Fifth element:"<     //Fifth element:3
   
    //front 和 back方法
    cout<<"First element: "<     cout<<"Last element: "<     //First element: 65
    //Last element: 10
   
    //erase方法
    iVector.erase(iVector.begin());
    PrintIntVector(iVector);
    //Vector: [30,30,2,3,4,1,10,65,30,30,2,3,4,1,10]
   
    //reverse_iterator使用方法
    INTVECTOR::reverse_iterator riter;
    riter = iVector.rbegin();

你可能感兴趣的:(C/C++)