C++11除了增加array類別,更新增了vector類別,
重點是它打破了以往字串不能更改大小的問題,
它將在程式執行中
自動執行動態記憶體配置
幫程式設計師省下許多麻煩
基本資料
- 相同的型態
- 類似陣列
- 可替代加入動態陣列
- 元素數目可在程式運行中改變
- 增加彈性 減少記憶體浪費
元素數目可為變數
Ex:
[code language=”cpp”]
#include <iostream>
#include <vector> //引入 <vector> 標頭檔
using namespace std;
int main(){
vector<int> str1(10); //建立初始包含10個整數型態的vecor物件
int n;
cout << "請輸入初始元素數目" << endl; cin >> n;
vector<int> str2(n); //元素數目可為變數
}<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>
[/code]
取得vector物件大小:
size(物件名稱);
取得vector物件在某位置的元素值:
at(元素位置);
Ex:
[code language=”cpp”]
#include <iostream>
#include <vector> //引入 <vector> 標頭檔
#include <algorithm> ////引入 <algorithm> 標頭檔
using namespace std;
int main(){
vector <int> str(10);
cout << str.size() << endl; //取得物件str大小
str={10,9,8,7,6,5,4,3,2,1};
//取出第(4+1)個值 (從0開始)
cout << str.at(4) <<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>< endl;
}
[/code]