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;
    }
  • 相关阅读:
    collection系列用法-defaultdict()
    collection系列用法-namedtuple()
    collection系列用法-deque双向队列
    Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
    python 【第四篇】:面向对象(一)
    python之lambda表达式
    python 【第三篇】:函数及参数
    LeetCode 648. Replace Words (单词替换)
    LeetCode 953. Verifying an Alien Dictionary (验证外星语词典)
    LeetCode 970. Powerful Integers (强整数)
  • 原文地址:https://www.cnblogs.com/love-ziji/p/12633211.html
Copyright © 2011-2022 走看看