Search⌘ K

- Solution

Understand how to manage resources efficiently by using std::array in Modern C++. Learn to modify array elements safely using both bracket and at access methods, and recognize how out-of-range access triggers exceptions. This lesson prepares you for advanced memory management with smart pointers in future lessons.

We'll cover the following...

Solution

C++
#include <array>
#include <iostream>
int main(){
std::cout << std::endl;
std::array<int, 4> arr= {1, 2, 3, 4};
for ( auto a: arr){ std::cout << a << " " ; }
std::cout << std::endl;
arr[0]=1000;
arr[2]=5;
for ( auto a: arr){ std::cout << a << " " ; }
std::cout << std::endl;
arr.at(0)= '2';
arr.at(2)= 'c';
for ( auto a: arr){ std::cout << a << " " ; }
std::cout << std::endl;
arr.at(100)= 'l';
}

Explanation

  • In line 8, we have initialized an std::array<int>.

  • In lines 13 and 14, we ...