Arrays & Introduction to Vectors
C++ supports fixed-size contiguous memory arrays, as well as dynamic STL vectors that resize automatically.
1 Fixed Arrays vs. Dynamic STL Vectors
Standard arrays are fixed in size at compilation time, and C++ does not perform out-of-bounds safety checks. To prevent buffer overflows, C++'s Standard Template Library (STL) provides **`std::vector`**, which manages memory dynamically on the heap and resizes as elements are added.
2 Vector & Matrix operations
Let's run a program defining static matrices and dynamic vectors, adding and accessing elements safely:
C++ — Arrays and Vectors
▶ Run Code
#include <iostream>
#include <vector> // Needed for std::vector
int main() {
// 1. Fixed-size array matrix
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
std::cout << "Matrix element [1][2]: " << matrix[1][2] << "\n";
// 2. Dynamic Vector
std::vector<int> numbers;
numbers.push_back(10); // Add elements dynamically
numbers.push_back(20);
numbers.push_back(30);
std::cout << "Vector Size: " << numbers.size() << "\n";
std::cout << "Vector elements: ";
for (int n : numbers) { // Modern range-based for loop
std::cout << n << " ";
}
std::cout << "\n";
return 0;
}
3 Code Challenge
Challenge: Write a program that declares a `std::vector` of doubles. Use a loop to populate it with the squares of numbers from 1.0 to 5.0. Output the size of the vector and iterate through it to print the values.