STL之vector

vector即动态数组,也叫向量。

直接上代码!

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    //构造
    vector<int> v1(3); //构造一个大小为3的向量,不赋值默认为0
    for (vector<int>::iterator it = v1.begin(); it < v1.end(); it++) //输出:000
        cout << *it;
    cout << endl;
    vector<int> v2{ 2,6,8 }; //赋值构造
    for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //输出:268
        cout << *it;
    cout << endl << v2.size() << endl; //size=3

    //重置大小
    v2.resize(4);
    for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //输出:2680
        cout << *it;
    cout << endl << v2.size() << endl; //size=4

    //元素获取
    cout << v2[1] << endl; //不检查下标是否越界,但速度较快
    cout << v2.at(1) << endl; //检查下标是否越界
    cout << v2.front() << endl; //输出:2
    cout << v2.back() << endl; //输出:0

    //追加
    v2.push_back(9);
    for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //输出:26809
        cout << *it;
    cout << endl << v2.size() << endl; //size:5

    //删除
    v2.erase(v2.end() - 2);
    for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //输出:2689
        cout << *it;
    cout << endl << v2.size() << endl; //size:4
    v2.clear();
    for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //无输出
        cout << *it;
    cout << endl << v2.size() << endl; //size:0

    //排序
    v2 = { 2,6,8,3,6,9 };
    sort(v2.begin(), v2.end()); //从小到大排序
    for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //输出:236689
        cout << *it;
    cout << endl;
    sort(v2.begin(), v2.end(),greater<int>()); //从大到小排序
    for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //输出:986632
        cout << *it;
    cout << endl;
    return 0;
}
posted @ 2020-04-06 10:08  你的名字_子集  阅读(441)  评论(1编辑  收藏  举报