美文网首页程序员
标准模板库(STL)之 vector 用法【初级】

标准模板库(STL)之 vector 用法【初级】

作者: Aliven888 | 来源:发表于2020-08-12 00:24 被阅读0次

    文档声明:
    以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。


    资料仅供学习交流使用。
    作者:Aliven888

    1、简述

    SDK官网对其描述是:

    Vectors are sequence containers representing arrays that can change in size.
    .
    Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.
    .
    Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.
    .
    Instead, vector containers may allocate some extra storage to accommodate for possible growth, and thus the container may have an actual capacity greater than the storage strictly needed to contain its elements (i.e., its size). Libraries can implement different strategies for growth to balance between memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing intervals of size so that the insertion of individual elements at the end of the vector can be provided with amortized constant time complexity (see push_back).
    .
    Therefore, compared to arrays, vectors consume more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.
    .
    Compared to the other dynamic sequence containers (deques, lists and forward_lists), vectors are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements from its end. For operations that involve inserting or removing elements at positions other than the end, they perform worse than the others, and have less consistent iterators and references than lists and forward_lists.

    2、接口函数

    2.1、向量迭代器

    名称 描述
    begin Return iterator to beginning (public member function )
    end Return iterator to end (public member function )
    rbegin Return reverse iterator to reverse beginning (public member function )
    rend Return reverse iterator to reverse end (public member function )
    cbegin Return const_iterator to beginning (public member function )
    cend Return const_iterator to end (public member function )
    crbegin Return const_reverse_iterator to reverse beginning (public member function )
    crend Return const_reverse_iterator to reverse end (public member function )

    2.2、向量尺寸接口

    名称 描述
    size Return size (public member function )
    max_size Return maximum size (public member function )
    resize Change size (public member function )
    capacity Return size of allocated storage capacity (public member function )
    empty Test whether vector is empty (public member function )
    reserve Request a change in capacity (public member function )
    shrink_to_fit Shrink to fit (public member function )

    2.3、向量元素操作接口

    名称 描述
    operator[] Access element (public member function )
    at Access element (public member function )
    front Access first element (public member function )
    back Access last element (public member function )
    data Access data (public member function )

    2.4、向量数值变更接口

    名称 描述
    assign Assign vector content (public member function )
    push_back Add element at the end (public member function )
    pop_back Delete last element (public member function )
    insert Insert elements (public member function )
    erase Erase elements (public member function )
    swap Swap content (public member function )
    clear Clear content (public member function )
    emplace Construct and insert element (public member function )
    emplace_back Construct and insert element at the end (public member function )

    3、接口函数用法

    3.1、向量迭代器介绍

        //定义一个迭代器,指向容器的起点
        //例如:vcVector[1, 2, 3, 4]   itBegin 指向 1
        //在C++11中引入了cbegin() 返回一个const类型的迭代器,和begin的区别就是,const类型的迭代器不能用于修改参数值。
        std::vector<int>::iterator itBegin = vcVector.begin();  
        
        //定义一个迭代器,指向容器的终点
        //例如:vcVector[1, 2, 3, 4]   itBegin 指向 4 的下一个位置,所以判断是常用 (itBegin != itEnd) 来表示遍历结束
        //在C++11中引入了cend() 返回一个const类型的迭代器,和end的区别就是,const类型的迭代器不能用于修改参数值。
        std::vector<int>::iterator itEnd = vcVector.end();  
        
        //返回逆向队列的第一个数据, 即容器的最后一个数据。
        //在C++11中引入了crbegin() 返回一个const类型的迭代器,和rbegin的区别就是,const类型的迭代器不能用于修改参数值。
        std::vector<int>::reverse_iterator itRbegin = vcVector.rbegin();
        
        //返回逆向队列的最后一个数据的下一个位置, 即容器的第一个数据再往前的一个位置
        //在C++11中引入了crend() 返回一个const类型的迭代器,和rend的区别就是,const类型的迭代器不能用于修改参数值。
        std::vector<int>::reverse_iterator itREnd = vcVector.rend();
        
    

    3.2、向量尺寸操作

    3.2.1 size()

        /***********  size()    ***********/
        //Returns the number of elements in the vector
        //返回向量中元素的数量
        int iSzie = vcVector.size();
    

    3.2.2 max_size()

        /***********  max_size()    ***********/
        //Returns the maximum number of elements that the vector can hold
        //返回向量可以容纳的最大元素数
        //int iMaxSize = vcVector.max_size();
    

    3.2.3 capacity()

        /***********  capacity()    ***********/
        //Returns the size of the storage space currently allocated for the vector, expressed in terms of elements.
        //返回当前为向量分配的存储空间的大小,以元素表示。
        int iCapacity = vcVector.capacity();
    

    3.2.4 resize(...)

        /*********** resize(n) 和 resize(n,x) ***********/
        //Resizes the container so that it contains n elements.
        //调整容器的大小,使其包含n个元素,或者n个x元素。
        //vcVector.resize(3);  //3 个容量的值都是默认 0
        vcVector.resize(3, 6); //3 个容量的值都是 6
    

    3.2.5 reserve(...)

        /***********  reserve(n) ***********/
        //Requests that the vector capacity be at least enough to contain n elements.
        //请求向量容量至少足以包含n个元素
        //修改后capacity()的返回值会发生变化
        int iCapacity = vcVector.capacity(); //修改前 iCapacity == 0
        vcVector.reserve(4);
        iCapacity = vcVector.capacity(); //修改后 iCapacity == 4
    

    3.2.6 empty()

        /***********  empty() ***********/
        //Returns whether the vector is empty (i.e. whether its size is 0).
        //返回向量是否为空(即其大小是否为0)。
        //true if the container size is 0, false otherwise.
        //如果容器大小为0,则为true,否则为false
        if (vcVector.empty)
        {
            cout << "vcVector is empty." << endl;
        }
    

    3.2.7 shrink_to_fit()

        /***********  shrink_to_fit() ***********/
        // C++11 引入的属性
        //Requests the container to reduce its capacity to fit its size.
        //要求容器减少其容量以适合其尺寸
        vcVector.push_back(1);
        vcVector.push_back(2);
        vcVector.push_back(3);
        int iCapacity = vcVector.capacity();   //修改前 iCapacity == 3
        vcVector.resize(10);  //重置尺寸
        vcVector.shrink_to_fit();
        iCapacity = vcVector.capacity();  //修改后 iCapacity == 10
    

    3.3、获取向量元素

    3.3.1 operator[]

        /***********  operator[] ***********/
        //Returns a reference to the element at position n in the vector container.
        //返回对向量容器中位置n处元素的引用。
        vcVector.push_back(1);
        vcVector.push_back(2);
        vcVector.push_back(3);
        int iValue = vcVector[1];  //iValue == 2
    

    3.3.2 at(...)

        /***********  at(n) ***********/
        //Returns a reference to the element at position n in the vector.
        //返回对向量中位置n处元素的引用。
        vcVector.push_back(1);
        vcVector.push_back(2);
        vcVector.push_back(3);
        int iValue = vcVector.at(1);  //iValue == 2
    

    3.3.3 front() 和 back()

        /***********  front() 和  back() ***********/
        //Returns a reference to the first(last) element in the vector.
        //返回对向量中第一个(最后一个)元素的引用。
        vcVector.push_back(1);
        vcVector.push_back(2);
        vcVector.push_back(3);
        int iValueFont = vcVector.front();  //获取位于起点位置的值
        int iValueBack = vcVector.back();   //获取位于终点位置的值
    

    3.3.4 data()

        /***********  data() ***********/
        //C++11 引入的
        //Returns a direct pointer to the memory array used internally by the vector to store its owned elements.
        //返回指向向量内部用于存储其拥有的元素的内存数组的直接指针。
        vcVector.push_back(1);
        vcVector.push_back(2);
        vcVector.push_back(3);
        int *iElements = vcVector.data();  //获取容器的全部值
        for (int i = 0; i < vcVector.size(); ++i, iElements++)
        {
            cout << "iElements[" <<  i << "] - value[" << *iElements << "]");
        }
    

    3.4、修改向量元素值

    3.4.1 assign(...)

        /***********  assign(...) ***********/
        //C++11 引入的
        //Assigns new contents to the vector, replacing its current contents, and modifying its size accordingly.
        //将新内容分配给向量,替换其当前内容,并相应地修改其大小。
    
        //assign 重置容器的值,包括尺寸,和resize()函数作用类似
        //例如:vcVector[1, 2, 3, 4, 5, 6]  --> vcVector[6, 6, 6]  
        vcVector.assign(3, 6);
    
        //也可以拷贝某个容器中的部分或者全部值
        ///例如:vcVector[1, 2, 3, 4, 5, 6] - vcChild[5, 6, 7]  --> vcVector[5, 6]  
        std::vector<int> vcChild;
        vcChild.push_back(5);
        vcChild.push_back(6);
        vcChild.push_back(7);
        std::vector<int>::iterator itChildBegin = vcChild.begin();
        itChildBegin = vcChild.begin();
        vcVector.assign(itChildBegin, itChildBegin + 2);
    

    3.4.2 push_back(...)

        /*********** push_back  ***********/
        //Adds a new element at the end of the vector, after its current last element.
        //The content of val is copied (or moved) to the new element.
        //在向量的最后一个元素之后的向量的末尾添加一个新元素。 val的内容被复制(或移动)到新元素。
        vcVector.push_back(4);
    

    3.4.3 pop_back(...)

        /*********** pop_back  ***********/
        //Removes the last element in the vector, effectively reducing the container size by one.
        //删除向量中的最后一个元素,从而有效地将容器大小减小了一个(移除容器的最后一个元素)。
        //例如:vcVector[1, 2, 3, 4]  --> vcVector[1, 2, 3] 
        vcVector.pop_back();
    

    3.4.4 insert(...)

        /*********** insert  ***********/
        //C++11 引入的
        //The vector is extended by inserting new elements before the element at the specified position, 
        //effectively increasing the container size by the number of elements inserted.
        //通过在指定位置的元素之前插入新元素来扩展向量,从而通过插入的元素数量有效地增加容器大小。
        std::vector<int>::iterator itBegin = vcVector.begin();  
        std::vector<int>::iterator itEnd = vcVector.end(); 
            
        //在起点位置插入元素 < 0 1 2 3 >
        vcVector.insert(itBegin, 0);
    
        //在终点位置插入元素
        //vcVector.insert(itEnd, 4);     //这个是错误写法,会导致程序崩掉
        vcVector.push_back(4);         //这个才是正确的写法
    
        //插入一个vector
        std::vector<int> vcChild;
        vcChild.push_back(5);
        vcChild.push_back(6);
        vcChild.push_back(7);
        itBegin = vcVector.begin(); //更新下迭代器
        vcVector.insert(itBegin, vcChild.begin(), vcChild.end());  //< 5 6 7 0 1 2 3 4 >
        itEnd = vcVector.end();     //更新下迭代器
        vcVector.insert(itEnd, vcChild.begin(), vcChild.end());   //< 5 6 7 0 1 2 3 4 5 6 7 >
    
        //只取vcChild的一部分
        std::vector<int>::iterator itChildBegin = vcChild.begin();
        itEnd = vcVector.end();     //更新下迭代器
        vcVector.insert(itEnd, itChildBegin, itChildBegin + 1);   //< 5 6 7 0 1 2 3 4 5 6 7 5 >
    

    3.4.5 erase(...)

        /*********** erase  ***********/
        //Removes from the vector either a single element (position) or a range of elements ([first,last))
        //从向量中删除单个元素(位置)或元素范围([first,last))
        //移除容器中的元素,以迭代器为对象进行操作
        //移除一个元素
        std::vector<int>::iterator itBegin = vcVector.begin();
        vcVector.erase(itBegin);
    
        //移除n个元素
        itBegin = vcVector.begin(); //刷新迭代器
        vcVector.erase(itBegin, itBegin + 2);
    

    3.4.6 swap(...)

        /*********** swap  ***********/
        //Exchanges the content of the container by the content of x,
        //which is another vector object of the same type. Sizes may differ.
        //用x的内容交换容器的内容,x是相同类型的另一个矢量对象。 大小可能有所不同。
        std::vector<int> vcChild;
        vcChild.push_back(5);
        vcChild.push_back(6);
        vcChild.push_back(7);
        vcVector.swap(vcChild);
    

    3.4.7 emplace(...) 和 emplace_back(...)

        /*********** emplace 和 emplace_back ***********/
        //C++11 引入的
        //The container is extended by inserting a new element at position. 
        //This new element is constructed in place using args as the arguments for its construction.
        //通过在位置插入新元素来扩展容器。 这个新元素是使用args作为其构造参数构建的。
        itBegin = vcVector.begin();
        vcVector.emplace(itBegin, 1);  //在迭代器指向的元素前插入一个元素
    
        vcVector.emplace_back(666);  //在容器的末尾插入一个元素
    

    4、注意事项

    1、当容器尺寸发生变化时(有元素被添或者删除时),迭代器必须刷新(重新获取),否则将导致程序崩掉。
    2、向量定义时可以指定大小(std::vector<int> vcValue[100];),也可以不指定(std::vector<int> vcValue;)。

    相关文章

      网友评论

        本文标题:标准模板库(STL)之 vector 用法【初级】

        本文链接:https://www.haomeiwen.com/subject/blccdktx.html