該數組是用於固定大小數組的容器。此容器環繞固定大小的數組,並且在衰減為指針時也不會丟失其長度信息。
為了利用數組,我們需要包括數組頭:
#include <array>
讓我們來看一個例子。
// CPP program to demonstrate working of array
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
// construction uses aggregate initialization
// double-braces required
array<int, 5> ar1{{3, 4, 5, 1, 2}};
array<int, 5> ar2 = {1, 2, 3, 4, 5};
array<string, 2> ar3 = {{string("a"), "b"}};
cout << "Sizes of arrays are" << endl;
cout << ar1.size() << endl;
cout << ar2.size() << endl;
cout << ar3.size() << endl;
cout << "\nInitial ar1:";
for (auto i:ar1)
cout << i << ' ';
// container operations are supported
sort(ar1.begin(), ar1.end());
cout << "\nsorted ar1:";
for (auto i:ar1)
cout << i << ' ';
// Filling ar2 with 10
ar2.fill(10);
cout << "\nFilled ar2:";
for (auto i:ar2)
cout << i << ' ';
// ranged for loop is supported
cout << "\nar3:";
for (auto &s:ar3)
cout << s << ' ';
return 0;
}
輸出:
Sizes of arrays are 5 5 2 Initial ar1:3 4 5 1 2 sorted ar1:1 2 3 4 5 Filled ar2:10 10 10 10 10 ar3:a b
相關用法
注:本文由純淨天空篩選整理自Shantanu Sharma.大神的英文原創作品 STD::array in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。