1 #include<iostream> 2 #include<array> 3 #include<exception> 4 5 6 void display(std::array<int, 10> &arr) 7 { 8 for (size_t i{}; i < arr.size(); ++i) //size_t代表unsigned int, i{} 相当于 i = 0, {}也可以对容器内部所有元素赋上初值0 9 { 10 std::cout << arr[i] << " "; 11 } 12 std::cout << std::endl; 13 } 14 void test01() 15 { 16 std::array<int, 10> volumn; 17 volumn.fill(5); //容器内所有都填入同样的数值 18 display(volumn); 19 20 try 21 { 22 volumn.at(10); //会抛出异常,而采用[]的方式会直接访问越界导致程序崩溃。 23 } 24 catch (std::exception &e) 25 { 26 std::cout << "out of bound" << std::endl; 27 } 28 29 if (volumn.empty()) //判断容器是否为空 30 { 31 std::cout << "the container has no elements" << std::endl; 32 } 33 else 34 { 35 std::cout << "the container has " << volumn.size() << " elements" << std::endl; 36 } 37 38 /*C11的遍历方式,atuo可以自动识别出数据类型,必须通过引用才能修改值*/ 39 int start = 1; 40 for (auto &value : volumn) 41 { 42 value = start; 43 ++start; 44 } 45 46 /*使用迭代器*/ 47 for (std::array<int, 10>::iterator vt = volumn.begin(); vt != volumn.end(); ++vt) 48 { 49 std::cout << *vt << " "; 50 } 51 std::cout << std::endl; 52 53 /*使用反向迭代器*/ 54 for (std::array<int, 10>::reverse_iterator vt = volumn.rbegin(); vt != volumn.rend(); ++vt) 55 { 56 std::cout << *vt << " "; 57 } 58 std::cout << std::endl; 59 for (auto vt = volumn.rbegin(); vt != volumn.rend(); ++vt) 60 { 61 std::cout << *vt << " "; 62 } 63 std::cout << std::endl; 64 /*将所有元素赋值为100*/ 65 volumn.assign(100); 66 display(volumn); 67 68 69 } 70 71 int main() 72 { 73 74 test01(); 75 system("pause"); 76 return 0; 77 }
5 5 5 5 5 5 5 5 5 5
out of bound
the container has 10 elements
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
100 100 100 100 100 100 100 100 100 100
请按任意键继续. . .