c++ array
定義
c++11添加了數組 array, 使用它需要包含 <array> 頭文件,定義為:
template<typename _Tp, std::size_t _Nm> struct array優點
array不會像c語言中的數組一樣會退化成T*。
#include <iostream> #include <array>using namespace std;void func(array<int, 8> & a) {cout << sizeof(a) << endl; }int main() {array<int, 8> a;cout << sizeof(a) << endl;func(a);return 0; }輸出:
32 32array 具有C風格的數組的優點,比如能夠隨機訪問、知道大小、賦值,同時,支持C++容器的部分功能
缺點
默認情況下,array中的元素值是隨機的
不像vector容器,array的swap操作時間復雜度是 O(N)
#include <iostream> #include <array> #include <algorithm>using namespace std;int main() {array<int, 8> a;for (int & e : a){cout << e << endl; // 內部是隨機值 }a.fill(6); // 全部賦值為6 cout << a.size() << ' ' << a.max_size() << endl; // 8 8for_each(a.begin(), a.end(), [](int & i) { // 遍歷cout << i << ' ';});a.begin();a.end();a.cbegin();a.cend();a.rbegin();a.rend();a.crbegin();a.crend();cout << *a.data() << endl;cout << a.front() << ' ' << a.back() << endl;int *p = a.data();array<int, 8> b;a == b;a != b;a < b;cout << get<7>(a) << endl;return 0; }?
轉載于:https://www.cnblogs.com/zuofaqi/p/10210480.html
總結