Arrays and Vectors in C++: Description & Usage With Examples
Learn how to store and manage collections of data using arrays and vectors. Master declaration, initialization, loops, and dynamic list operations.
- What arrays and vectors are and why they are useful
- How to declare and initialize arrays
- How to loop through arrays for input and output
- How vectors work and when to use them over arrays
- Key vector functions: push_back, size, clear, and empty
1Why use arrays and vectors?
When you need to store multiple values of the same type, like a list of test scores, student names, or temperatures, you need a way to group them together. That is exactly what arrays and vectors do.
Without an array:
int m1, m2, m3, m4, m5;
With an array:
int marks[5];
Arrays group values together, making your code cleaner, easier to manage, and more scalable. Vectors take this a step further by allowing dynamic resizing.
2Arrays in C++
An array is a fixed-size collection of elements of the same data type. The size must be known at compile time.
Declaration
int numbers[5]; // creates space for 5 integers
Initialization
int numbers[5] = {10, 20, 30, 40, 50};
You can also omit the size if you are initializing:
int numbers[] = {10, 20, 30}; // compiler counts 3 elements
Accessing elements
Array indexing starts at 0. The first element is at index 0, the second at index 1, and so on.
cout << numbers[0]; // prints 10 numbers[2] = 99; // changes the 3rd element to 99
3Looping through arrays
Use a for loop to access each element in an array. The loop counter serves as the index.
int scores[5] = {88, 76, 92, 85, 69}; for (int i = 0; i < 5; i++) { cout << "Score " << i << ": " << scores[i] << endl; }
4Inputting into an array
You can read values from the user directly into an array using cin inside a loop.
int marks[5]; cout << "Enter marks of 5 students: "; for (int i = 0; i < 5; i++) { cin >> marks[i]; }
5Common mistakes with arrays
numbers[5] in a size 5 array causes undefined behavior. Valid indices are 0 to 4. The compiler will not stop you, but your program may crash or behave unpredictably.
i < 5, not i <= 5.
6When to use vectors
Arrays are fixed in size. If you need a collection that can grow or shrink, use a vector. Vectors are part of the C++ Standard Template Library (STL).
To use vectors, include:
#include <vector> using namespace std;
Declaring vectors
vector<int> numbers; // empty vector of integers
Initialization
vector<int> scores = {85, 90, 78};
Add elements
scores.push_back(95); // adds 95 to the end
Access elements
cout << scores[0]; // prints 85 scores[1] = 100; // changes the second element to 100
7Looping through vectors
You can loop through a vector using a traditional for loop with size(), or use a range-based for loop.
Traditional loop
vector<int> values = {10, 20, 30, 40}; for (int i = 0; i < values.size(); i++) { cout << values[i] << endl; }
Range-based for loop (C++11 and later)
for (int val : values) { cout << val << endl; }
8Vector functions you should know
| Function | Description |
|---|---|
push_back(x) | Adds x to the end of the vector |
size() | Returns the number of elements |
clear() | Removes all elements |
empty() | Returns true if the vector is empty |
empty() before accessing elements if there is a chance the vector could be empty. Accessing an empty vector causes undefined behavior.
9Example: Average of N numbers using a vector
This example demonstrates reading N values from the user, storing them in a vector, and calculating the average.
#include <iostream> #include <vector> using namespace std; int main() { int n; cout << "Enter number of elements: "; cin >> n; vector<int> nums; int input; int sum = 0; for (int i = 0; i < n; i++) { cin >> input; nums.push_back(input); sum += input; } double average = (double) sum / nums.size(); cout << "Average: " << average << endl; return 0; }
10Mini exercises
- Create an array of size 10 and store the first 10 square numbers (1, 4, 9, 16, ...).
- Write a program that finds the maximum value in an array of integers.
- Use a vector to read N values from the user, and then print only the even numbers.
- Initialize a vector with {1, 2, 3}, then add 4 and 5 using
push_back, and print all values.
Hint: For the square numbers, multiply i * i inside the loop. For even numbers, check num % 2 == 0.
