日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

        歡迎訪問 生活随笔!

        生活随笔

        當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

        编程问答

        vector基础操作

        發(fā)布時(shí)間:2025/4/5 编程问答 21 豆豆
        生活随笔 收集整理的這篇文章主要介紹了 vector基础操作 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
        • //vector< T> vec; //構(gòu)造一個(gè)名為vec的儲(chǔ)存數(shù)據(jù)類型為T的動(dòng)態(tài)數(shù)組。其中T為需要儲(chǔ)存的數(shù)據(jù)類型
        • //初始時(shí)vec為空
        • //push_back 末尾添加一個(gè)元素
        • //pop_back 在末尾彈出一個(gè)元素
        • //size 獲取長度
          • size_type size() const; Return size Returns the number of elements in the vector.
          • This is the number of actual objects held in the vector, which is not
            necessarily equal to its storage capacity.
        • //clear 清空
        • //修改vector其中的某個(gè)元素,直接賦值,比如vec[1]=3; //修改vector其中的某個(gè)元素,直接賦值,比如vec[1]=3;
        • //vector的方法size()可以直接獲取長度,通過[]可以直接獲取其中的元素,和數(shù)組相同

        • //clear()會(huì)清空vector中內(nèi)容,但是不會(huì)重新分配空間

          • 如果需要清空vector的內(nèi)存,一種典型的方法是使用交換, 即使用一個(gè)空的vector和原來的vector進(jìn)行交換,完成內(nèi)存的釋放
        vector< int>vec; { vector< int> x; vec.swap(x); }
        • 下面是官方文檔關(guān)于clear()的描述
          C++官方文檔

        Clear content
        Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.

        A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap:
        vector().swap(x); // clear x reallocating

        #include<iostream> #include<vector> using namespace std; int main(void) {vector<int> vec; //創(chuàng)建動(dòng)態(tài)數(shù)組,未知大小vec.push_back(1); //添加元素1,此時(shí)為{1}vec.push_back(2); //添加元素2,此時(shí)為{1,2}vec.push_back(3); //添加元素3,此時(shí)為{1,2,3}vec[1] = 3; //下標(biāo)為1的元素被修改為3,此時(shí)為{1,3,3}vec[2] = 2; //下標(biāo)為2的元素被修改為2, 此時(shí)為{1,3,2}for (int i = 0; i < vec.size(); i++)printf("%d\n",vec[i]);return 0; }

        轉(zhuǎn)載于:https://www.cnblogs.com/FlyerBird/p/9052561.html

        總結(jié)

        以上是生活随笔為你收集整理的vector基础操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

        如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。