-
Notifications
You must be signed in to change notification settings - Fork 0
Array
Sgt. Mahdi edited this page Apr 9, 2025
·
11 revisions
array is a collection of values with the similar type in a contiguous memory location. there are two types of array: dynamic and static.
Static arrays has a fixed size which means you have to specify the number of elements at compile time and once you set the size of the array, it can't be changed.
- Faster than dynamic array.
- Values will be stored in the stack memory
- The size of array must be specified at complie time.
int main() {
int array[5];
// Or you can use std::array<type, size> which gives you more helpful methods
for (int i = 0; i < 5; i++) {
array[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
std::cout << "[" << &array[i] << "]: " << array[i] << std::endl;
}
}
Dynamic array is a data structure allows us to add and remove data into an array without having a fixed size. A good example of this data structure is Vector. You want to use Dynamic array usually when you don't know how many the added values would be.
- You don't need to specify the number of elements.
- It's slower than static array due to heap allocation.
int main() {
std::vector<int> dynamicArray;
int amountOfData = 1000;
for (int i = 0; i < amountOfData; i++) {
dynamicArray.push_back(i);
}
for (int i = 0; i < amountOfData; i++) {
std::cout << "[" << &dynamicArray[i] << "]: " << dynamicArray[i] << std::endl;
}
}
Tip
std::array<Type, Size> is a static array
std::vector<Type> is a dynamic array
in this repository you see how vector works: