STL 之vector 用法

作为一名ACM的萌新~~STL的用法不是很熟练,特意总结了一些,以供参考。

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct student
{
    int id,age;
    string name;
    bool operator<(const student&a)      //重载<运算符
    {
        if(id!=a.id)
            return id<a.id;
        else if(age!=a.age)
            return age<a.age;
        else
            return name<a.name;
    }
};
bool cmp(const student&a ,  const student&b)
{
     return a.id>b.id;
}


int main()
{
    vector<int>v;              //一维向量
    v.push_back(3);         //在末尾插入元素3
    v.pop_back();             //删除最后的元素
    cout<<v.empty();       //输出是否为空
    v.resize(50);              //改变向量长度
    v.clear();                   //清空所有元素
    v.insert(v.begin()+5,20);//new function, insert data
    v.erase(v.begin()+2);//delete the i+2th element
    v.erase(v.begin()+3,v.begin()+8);//delete district from i to j-1;
    reverse(v.begin(),v.end());//the function of reverse all the element
    cout<<v.size()<<endl;//get the size of v
    v.clear();//clear everything

    vector<int>vt[3];                      //二维向量
    vt[0].push_back(3);                //在各行向量插入元素
    vt[1].push_back(a);
    vt[2].push_back(5);
    for(int i=0;i<3;++i)
        cout<<vt[i][0]<<endl;          //支持按下标访问
    vector<int>::iterator it;           //声明该种类型的迭代器,并使用迭代器遍历元素
    for(it=vt[0].begin();it!=vt[0].end();it++)
        cout<<*it<<endl;

    vector<string>vs;                  //string类型向量
    vector<string>::iterator t;
    string s;
    getline(cin,s);//use for string
    vs.push_back(s);
    char str[200];
    cin.get(str,100);//use for char array
    vs.push_back(str);
    for(t=vs.begin();t!=vs.end();++t)
        cout<<*t<<endl;//use iterator to output element;
    cout<<endl;

    student stu[3];
    for(int i=0;i<3;++i)
    {
        stu[i].id=i+1;
        stu[i].age=i+17;
        stu[i].name='A'+i;
    }
    vector<student>vst;                       //结构体向量
    vector<student>::iterator st;          //声明该种结构体类型的迭代器
    for(int i=0;i<3;++i)
        vst.push_back(stu[i]);
    for(st=vst.begin();st!=vst.end();++st)
        cout<<(*st).id<<" "<<(*st).age<<" "<<(*st).name<<endl;
    vst[2].id=5;
    sort(vst.begin(),vst.end(),cmp);     //对结构体向量进行排序
}

发布了25 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/pgs1004151212/article/details/51449730