C++ stl 學習2 -- array
阿新 • • 發佈:2020-07-17
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).
#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; }
}