天天看點

C++ vector數組用法記錄定義方法vector<type>name  其中type為變量類型,name為vector數組名稱注意:使用vector需要在頭檔案添加加 #include <vector>vector常用函數:拓展小知識:使用sort()進行排序使用sort()需要在頭檔案添加#include <algorithm>

定義方法

vector<type>name  其中type為變量類型,name為vector數組名稱

注意:使用vector需要在頭檔案添加加 #include <vector>

vector常用函數:

push_back(elem):在數組最後添加資料

pop_back() :去掉數組最後一個元素

size():傳回數組中實際存儲的數目

clear():清除數組中的所有元素

拓展小知識:使用sort()進行排序

使用sort()需要在頭檔案添加#include <algorithm>

一個執行個體:

#include <string.h>

#include <vector>

#include <iostream>

#include <algorithm>

using namespace std; i

nt main() {

vector<int>obj;

obj.push_back(1);

obj.push_back(3);

obj.push_back(0);

sort(obj.begin(),obj.end());//從小到大

cout<<"從小到大:"<<endl;

for(int i=0;i<obj.size();i++)

{ cout<<obj[i]<<","; }

cout<<"\n"<<endl;

cout<<"從大到小:"<<endl;

reverse(obj.begin(),obj.end());//從大到小

for(int i=0;i<obj.size();i++) {

cout<<obj[i]<<","; } return 0;

}

c+