C++ std::array (C++11) šŸŽÆ

beginner
9 min

C++ std::array (C++11) šŸŽÆ

Welcome to our deep dive into the std::array in C++! This powerful container is part of the C++11 standard library, making it a great tool for modern C++ programming. Let's learn together! šŸ¤

Introduction šŸ“

In C++, we often use arrays to store a collection of elements. However, they lack the benefits of dynamic containers like std::vector. std::array combines the efficiency of arrays with the convenience of dynamic containers.

Creating an std::array šŸ’”

To create an std::array, we first include the <array> header and then use the std::array template to specify the number of elements and their type. Here's an example:

cpp
#include <iostream> #include <array> int main() { std::array<int, 5> myArray; // Creating an array of 5 integers // Accessing the elements myArray[0] = 10; myArray[1] = 20; myArray[2] = 30; myArray[3] = 40; myArray[4] = 50; // Printing the elements for (int i = 0; i < myArray.size(); ++i) { std::cout << myArray[i] << " "; } return 0; }

šŸ“ Note: The std::array has a size() method that returns the number of elements it holds.

std::array Advantages šŸ’”

  1. Efficiency: std::array provides the same efficiency as regular arrays due to the fixed size.
  2. Dynamic Allocation: Even though the size is fixed, we can still initialize the array dynamically.
  3. Range Checking: Compilers can perform range checking to avoid out-of-bounds errors.

Common std::array Operations šŸ’”

  1. Accessing Elements: Just like regular arrays, we can access elements using indexing.
  2. Resizing: Unlike regular arrays, std::array can be resized using the std::array::resize() function.
  3. Iteration: We can iterate through the elements using range-based for loops.

Advanced Example šŸŽÆ

Here's an example where we use std::array to implement a simple 3x3 matrix with matrix operations.

cpp
#include <iostream> #include <array> int main() { std::array<std::array<int, 3>, 3> matrixA = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; std::array<std::array<int, 3>, 3> matrixB = { {10, 11, 12}, {13, 14, 15}, {16, 17, 18} }; // Matrix addition std::array<std::array<int, 3>, 3> result; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { result[i][j] = matrixA[i][j] + matrixB[i][j]; } } // Printing the result for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { std::cout << result[i][j] << " "; } std::cout << "\n"; } return 0; }

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What is the output of the above code?

Conclusion šŸ“

In this lesson, we've learned about std::array, a powerful container in C++ that combines the efficiency of arrays with the convenience of dynamic containers. We've also seen a practical example of using std::array to implement a simple matrix with matrix operations. Keep exploring and implementing to strengthen your understanding! šŸš€

Happy coding! šŸ¤—