In C++, you have several options for working with arrays:
1. Static Arrays: These are fixed-size arrays where the size is known at compile time.
You declare them like this:
int myArray[5]; // Declares an integer array with a fixed size of 5
The size cannot be changed during runtime.
2. Dynamic Arrays (with new and delete): You can use dynamic memory allocation to create
arrays with sizes determined at runtime:
int* dynamicArray = new int[10]; // Creates a dynamically allocated integer array of size 10
// ... Use dynamicArray ...
delete[] dynamicArray; // Deallocates the dynamically allocated memory
Be sure to deallocate the memory using delete[] when you're done to avoid memory leaks.
3. std::vector: The C++ Standard Library provides the std::vector container, which is a dynamic array with many convenient features. It dynamically manages memory for you:
#include <vector>
std::vector<int> myVector; // Declares a dynamic array (vector) of integers
myVector.push_back(42); // Adds an element to the end
int value = myVector[0]; // Access elements like an array
You don't need to worry about memory management; std::vector takes care of it for you.
4. std::array: If you need a fixed-size array with some additional features like size checking, you can use std::array:
#include <array>
std::array<int, 5> myArray; // Declares a fixed-size array of integers with size 5
myArray[0] = 42; // Access elements like an array
The size is known at compile-time, but it provides some safety features compared to C-style arrays.
To embed this project on your website, copy the following code and paste it into your website's HTML: