automyArray1{std::to_array<int,5>({9,7,5,3,1})};// Specify type and sizeautomyArray2{std::to_array<int>({9,7,5,3,1})};// Specify type only, deduce sizeautomyArray3{std::to_array({9,7,5,3,1})};// Deduce type and size
std::array<int,5>myArray;myArray={0,1,2,3,4};// okaymyArray={9,8,7};// okay, elements 3 and 4 are set to zero!myArray={0,1,2,3,4,5};// not allowed, too many elements in initializer list!
std::arraymyArray{9,7,5,3,1};myArray.at(1)=6;// array element 1 is valid, sets array element 1 to value 6myArray.at(9)=10;// array element 9 is invalid, will throw a runtime error
#include<array>#include<iostream>voidprintArray(conststd::array<int,5>&myArray){for(autoelement:myArray)std::cout<<element<<' ';std::cout<<'\n';}intmain(){std::arraymyArray5{9.0,7.2,5.4,3.6,1.8};// type deduced as std::array<double, 5>printArray(myArray5);// error: printArray expects a std::array<int, 5>return0;}
#include<array>#include<cstddef>#include<iostream>// printArray is a template functiontemplate<typenameT,std::size_tsize>// parameterize the element type and sizevoidprintArray(conststd::array<T,size>&myArray){for(autoelement:myArray)std::cout<<element<<' ';std::cout<<'\n';}intmain(){std::arraymyArray5{9.0,7.2,5.4,3.6,1.8};printArray(myArray5);std::arraymyArray7{9.0,7.2,5.4,3.6,1.8,1.2,0.7};printArray(myArray7);return0;}
#include<iostream>#include<array>intmain(){std::arraymyArray{7,3,1,9,5};// Iterate through the array and print the value of the elementsfor(inti{0};i<myArray.size();++i)std::cout<<myArray[i]<<' ';std::cout<<'\n';return0;}
#include<array>#include<iostream>intmain(){std::arraymyArray{7,3,1,9,5};// std::array<int, 5>::size_type is the return type of size()!for(std::array<int,5>::size_typei{0};i<myArray.size();++i)std::cout<<myArray[i]<<' ';std::cout<<'\n';return0;}
#include<array>#include<iostream>intmain(){std::arraymyArray{7,3,1,9,5};// Print the array in reverse order.for(autoi{myArray.size()};i-->0;)std::cout<<myArray[i]<<' ';std::cout<<'\n';return0;}
#include<array>#include<iostream>structHouse{intnumber{};intstories{};introomsPerStory{};};intmain(){std::array<House,3>houses{};houses[0]={13,4,30};houses[1]={14,3,10};houses[2]={15,3,40};for(constauto&house:houses){std::cout<<"House number "<<house.number<<" has "<<(house.stories*house.roomsPerStory)<<" rooms\n";}return0;}
输出结果如下:
123
House number 13 has 120 rooms
House number 14 has 30 rooms
House number 15 has 120 rooms
// This works as expectedstd::array<House,3>houses{// initializer for houses{// 额外的大括号表明接下来初始化数组成员{13,4,30},// initializer for array element 0{14,3,10},// initializer for array element 1{15,3,40},// initializer for array element 2}};