zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Vue自定义组件
    Vuex状态管理总结
    关于状态管理模式
    Vue路由实现页面跳转的两种方式(router-link和JS)
    Vue过渡效果的实现
    Vue中的DOM操作
    SASS 和 LESS 的区别
    Vue计算属性和侦听器
    zabbix 内置变量
    /proc 目录下文件详解
  • 原文地址:https://www.cnblogs.com/love-ziji/p/12633211.html
Copyright © 2011-2022 走看看