日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

vector基础操作

發(fā)布時間:2025/4/5 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vector基础操作 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
  • //vector< T> vec; //構造一個名為vec的儲存數(shù)據(jù)類型為T的動態(tài)數(shù)組。其中T為需要儲存的數(shù)據(jù)類型
  • //初始時vec為空
  • //push_back 末尾添加一個元素
  • //pop_back 在末尾彈出一個元素
  • //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其中的某個元素,直接賦值,比如vec[1]=3; //修改vector其中的某個元素,直接賦值,比如vec[1]=3;
  • //vector的方法size()可以直接獲取長度,通過[]可以直接獲取其中的元素,和數(shù)組相同

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

    • 如果需要清空vector的內存,一種典型的方法是使用交換, 即使用一個空的vector和原來的vector進行交換,完成內存的釋放
vector< int>vec; { vector< int> x; vec.swap(x); }
  • 下面是官方文檔關于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)建動態(tài)數(shù)組,未知大小vec.push_back(1); //添加元素1,此時為{1}vec.push_back(2); //添加元素2,此時為{1,2}vec.push_back(3); //添加元素3,此時為{1,2,3}vec[1] = 3; //下標為1的元素被修改為3,此時為{1,3,3}vec[2] = 2; //下標為2的元素被修改為2, 此時為{1,3,2}for (int i = 0; i < vec.size(); i++)printf("%d\n",vec[i]);return 0; }

轉載于:https://www.cnblogs.com/FlyerBird/p/9052561.html

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。