Arrays and Vectors
💻 C++Store collections with raw arrays and the safer, resizable std::vector.
A raw array has a fixed size and does not know its own length. std::vector grows, shrinks and manages its memory.
- Create and loop over arrays.
- Use vector methods.
- Avoid out-of-bounds access.
Raw Arrays
A raw array has a fixed size set at compile time. There is no bounds checking, so reading past the end is undefined behaviour.
int scores[5] = {88, 74, 91, 65, 52};
for (int i = 0; i < 5; i++) {
std::cout << scores[i] << "\n";
}std::vector
A vector knows its size, grows automatically and is the default choice for collections.
#include <vector>
std::vector<int> scores = {88, 74, 91};
scores.push_back(65);
for (int score : scores) {
std::cout << score << "\n";
}
std::cout << scores.size() << "\n";Safe Access
Use at() when an index comes from outside your control. It throws instead of reading invalid memory. Use range-based for loops when you do not need the index.
Practice
- Create a vector of five names and print them.
- Calculate the total and average of a vector of scores.
- Explain why vector is safer than a raw array.
Hands-on exercise
Read six scores into a vector.
1. Print the highest and lowest.
2. Print the average to two decimal places.
3. Print each score above the average.
Recap
Raw arrays are fixed and unsafe at the edges. std::vector is the practical default for collections.
Example
int scores[5] = {88, 74, 91, 65, 52};
for (int i = 0; i < 5; i++) {
std::cout << scores[i] << "
";
}
Exercises
1. Print the highest and lowest.
2. Print the average to two decimal places.
3. Print each score above the average.
Expected Output
High, low, average and the above-average scores.
Lesson Nav
C++ Course
0/9 lessons completed
- 1 Your First C++ Program Tutorial
- 2 Variables, Types and Input Tutorial
- 3 Conditions and Loops Tutorial
- 4 Functions and Parameters Tutorial
- 5 Arrays and Vectors Tutorial
- 6 Pointers and References Tutorial
- 7 Classes and Objects Tutorial
- 8 The STL: Containers and Algorithms Tutorial
- 9 Project: A Console Grade Book Project