1. 程式人生 > 實用技巧 >C++ stl 學習2 -- array

C++ stl 學習2 -- array

array是固定大小的陣列,和我們用的 [ ] 形式陣列差不多。

特點

1. 只儲存裡面元素,連元素大小都不儲存 Internally, an array does not keep any data other than the elements it contains (not even its size, which is a template parameter, fixed on compile time)

2. 大小為0是合法的,但是不要解引用。Zero-sized arrays are valid, but they should not be dereferenced (members

front,back, anddata).

常見操作 array<int, 6> arr {1,2,3,4,5,6}; arr.begin() Return iterator to beginning (public member function ) arr.end() Return iterator to end (public member function ) arr.rbegin() // 翻轉begin Return reverse iterator to reverse beginning (public member function ) arr.rend() // 翻轉end Return reverse iterator to reverse end (public member function ) arr.cbegin() // const begin的意思 Return const_iterator to beginning (public member function ) arr.cend() // const end的意思 Return const_iterator to end (public member function ) arr.crbegin() // const rbegin 的意思 Return const_reverse_iterator to reverse beginning (public member function ) arr.crend() // const rbegin 的意思 Return const_reverse_iterator to reverse end (public member function ) arr.size() Return size (public member function ) arr.max_size() // 永遠和arr.size()一樣是初始化的那個數字即 array <int ,6> 中的6 Return maximum size (public member function ) arr.empty() Test whether array is empty (public member function ) arr[i] //不檢查下標是否越界 Access element (public member function ) arr.at(i) //會檢查下標是否越界 Access element (public member function ) arr.front() // 返回引用,可以當左值,第一個元素 Access first element (public member function ) arr.back() // 返回引用,可以當左值,最後一個元素 Access last element (public member function ) arr.data() //返回指向陣列的指標 Get pointer to data (public member function )
Modifiers arr.fill(num) // 把陣列中所有元素都填為num Fill array with value (public member function ) arr.swap(arr2) // 同另外一個數組交換元素,同類型,同大小 Swap content (public member function ) 當反向遍歷時,迭代器++ 其實是迭代器 --

#include <iostream>
#include <array>
using namespace std;

int main(void)
{
    array<int
,0> test; cout << test.size() << endl; cout << test.empty() << endl; cout << "==============" << endl; array<int, 6> a = {0, 1, 2, 3, 4, 5}; for (auto i : a) { cout << a[i] << endl; } cout << "==============" << endl; cout << a.size() << endl; cout << "==============" << endl; for (auto it = a.data(); it != a.end(); it++) { cout << *it << endl; } cout << a[7]; // 不會檢查是否越界,返回一個隨機值 //cout << a.at(7); // 會檢查越界,編譯不過 for (auto it = a.rbegin(); it != a.rend(); it++) { cout << *it << endl; }
}