1、靜态數組的基本操作
int a[5] = {0, 3, 4, 6, 2};
1.1 數組的周遊
1.1.1 傳統的for循環周遊
int size = sizeof(a) / sizeof(*a);
for(int i = 0; i < size; i++)
cout << a[i] << " ";
sizeof()是一個操作符(operator),傳回對象或類型所占記憶體空間的位元組數。
sizeof(a),傳回數組a所占記憶體空間的位元組數;sizeof(*a),傳回數組a首元素所占記憶體空間的位元組數。兩者相除即為數組長度。
1.1.2 C++11基于範圍的for循環周遊
for(int& item:a)
cout << item << " ";
for依次循環,item依次作為每個元素的引用。
1.2 數組的sort排序
#include <algorithm>
using namespace std;
sort()包含在頭檔案<algorithm>中,定義在命名空間std中。
sort(a, a + size);
for(int& item:a)
cout << item <<" ";
sort()可以傳入三個參數。第一個參數為要排序數組的首位址,第二個參數為要排序數組的尾位址,第三個參數制定排序類型(從小到大or從大到小)。第三個參數可以省略,預設從小到大排;且第三個參數用起來比較麻煩,若有從大到小的需求,可以先從小到大排,之後倒序輸出。
2、基于vector容器的動态數組的基本操作
數組的大小不能發生變化,需要在初始化時指定數組的大小。有時它會非常不友善并可能造成浪費。是以,大多數程式設計語言都提供内置的動态數組,它仍然是一個随機存取的清單資料結構,但大小是可以發生改變的。例如,在 C++ 中的vector。
#include <vector>
用到vector模闆類時,要注意引用頭檔案<vector>。
2.1 定義及初始化
// 1. initialize
vector<int> v0;
vector<int> v1(5, 0);//v1有5個元素,均為0
// 2. make a copy
vector<int> v2(v1.begin(), v1.end());
vector<int> v3(v2);
// 3. cast an array to a vector
int a[5] = {0, 1, 2, 3, 4};
vector<int> v4(a, *(&a + 1));
定義v4時,傳入兩個參數a和*(&a+1),兩個都是指針。a指向數組的首元素位址,&a為指向數組指針的指針,加一後就直接跨越了一個數組長度,再用*取值後,*(&a + 1)為指向數組尾元素的位址。
2.2 三種周遊方式
cout << "[Version 1] The contents of v4 are:";
for (int i = 0; i < v2.size(); ++i) {
cout << " " << v2[i];
}
cout << endl;
cout << "[Version 2] The contents of v4 are:";
for (int& item : v4) {
cout << " " << item;
}
cout << endl;
cout << "[Version 3] The contents of v4 are:";
for (auto item = v4.begin(); item != v4.end(); ++item) {
cout << " " << *item;
}
cout << endl;
vector用方括号[]加數字的方式通路内部具體的某個元素。
v.size()傳回vector的長度。
v.begin()傳回vector的首位址,v.end傳回vector的尾位址。
auto自身并不是一種資料類型,其隻是一種給對象自動比對類型的機制。
2.3 排序及在尾部插入、删除
// sort
sort(v4.begin(), v4.end());
// add new element at the end of the vector
v4.push_back(-1);
// delete the last element
v4.pop_back();
v.push_back(x)在vector尾部添加元素x,v.pop_back()删除最後一個元素。
原創:秋沐霖
部落格首頁:https://www.cnblogs.com/HL-space/
歡迎轉載,轉載請注明出處。
出錯之處,敬請交流、雅正!
創作不易,您的 " 推薦 " 和 " 關注 " ,是給我最大的鼓勵!