Arrays in C++

Arrays in C++ are collections of elements of the same data type stored in contiguous memory locations. They allow efficient storage and access of multiple values using a single variable name with index positions.

1. Types of Arrays in C++

C++ supports different types of arrays including single-dimensional, multi-dimensional, dynamic arrays, STL arrays, and vectors.

  • Single-dimensional array: Stores elements in a linear sequence.
  • Multi-dimensional array: Stores elements in rows and columns.
  • Dynamic array: Allocated at runtime using new keyword.
  • Pointer arrays: Arrays that store memory addresses.
  • STL array: Fixed-size array provided by library.
  • Vector: Dynamic resizable array from STL.

2. Single-Dimensional Array

A single-dimensional array in C++ stores elements linearly and is accessed using a single index.

  • Example: int arr[5] = {1, 2, 3, 4, 5}; cout << arr[2]; // Output: 3

3. Multi-Dimensional Array

Multi-dimensional arrays store data in tabular form using multiple indices.

  • Example: int matrix[2][3] = {{1,2,3},{4,5,6}}; cout << matrix[1][2]; // Output: 6

4. Dynamic Arrays

Dynamic arrays in C++ are allocated at runtime using the new keyword and released using delete.

  • Example: int *arr = new int[5]; arr[0] = 10; arr[1] = 20; delete[] arr;

5. Pointer Arrays

Pointer arrays are arrays that store the addresses of variables or other arrays.

  • Example: int a = 10, b = 20; int *ptr[2] = {&a, &b}; cout << *ptr[1]; // Output: 20

6. STL Array

C++ provides the header which offers a safer and more feature-rich fixed-size array.

  • Example: #include array arr = {1, 2, 3}; cout << arr[1]; // Output: 2

7. Vector (Dynamic Array)

Vector is part of the C++ Standard Template Library (STL) and allows dynamic resizing of arrays.

  • Example: #include vector v = {1,2,3}; v.push_back(4); cout << v[3]; // Output: 4