C++ Arrays vs std::vector — Complete Beginner Guide
Learning Objectives
- Declare and index a fixed size array
- Grow and shrink a std::vector at runtime
- Compare safety, size, and ergonomics
- Choose the right container for a task
The Problem Arrays Solve
Sometimes you need a row of related values under one name. Instead of score1, score2, and score3, you keep one sequence and reach each element by position. That position is called an index, and counting starts at zero.
Fixed Size Arrays
A plain array has a size fixed at creation. You declare the element type and the count.
#include <iostream>
int main() {
int scores[3] = {70, 85, 92};
for (int i = 0; i < 3; i++) {
std::cout << scores[i] << std::endl;
}
return 0;
}
| Property | Fixed Array |
|---|---|
| Size | Chosen once at creation |
| Growth | Not supported directly |
| Storage | Often on the stack when small |
| Bounds checking | Not automatic |
Array Traps
Writing past the last index corrupts memory silently. Forgetting the ending index also creates off by one bugs. The type system stores only elements, not the count, so many functions need an extra length parameter.
int values[5] = {};
// valid indexes: 0, 1, 2, 3, 4
// values[5] is out of range and dangerous
Dynamic Vectors
std::vector is a standard library container that owns a resizable array. Include the vector header to use it.
#include <iostream>
#include <vector>
int main() {
std::vector<int> scores;
scores.push_back(70);
scores.push_back(85);
scores.push_back(92);
for (int value : scores) {
std::cout << value << std::endl;
}
return 0;
}
The vector starts empty, grows as you add elements, and cleans up its memory automatically when it goes out of scope.
Side by Side Comparison
| Feature | Array | vector |
|---|---|---|
| Size change | Fixed | Growable |
| Knows length | No | Yes via size method |
| Bounds safety | Manual care | Prefer at or checked use |
| Syntax | Square brackets | Brackets or methods |
| Performance | Minimal overhead | Small overhead, still fast |
| Copy behavior | Element wise | Deep copy by default |
Common vector Operations
#include <vector>
#include <string>
std::vector<std::string> names;
names.push_back("Ada");
names.push_back("Linus");
std::string first = names[0];
bool empty = names.empty();
size_t count = names.size();
names.pop_back(); // removes the last entry
| Method | What It Does |
|---|---|
| push_back | Append one element |
| pop_back | Remove last element |
| size | Number of elements currently stored |
| empty | True when no elements remain |
| clear | Remove all elements |
| at | Checked access that throws on bad index |
Prefer at while learning because invalid positions raise an exception instead of corrupting memory.
Range Based Loops
Both containers work with range based for. The vector version reads especially cleanly.
std::vector<int> data = {1, 2, 3};
for (int n : data) {
std::cout << n << " ";
}
Add ampersand before the loop variable when you need to modify elements in place.
When To Pick Which
| Choose Array When | Choose vector When |
|---|---|
| Size is truly constant | Size is unknown up front |
| Tiny stack buffers | Data grows or shrinks |
| Interfacing with C style APIs | You want safe length knowledge |
| Performance critical fixed data | General application logic |
As a beginner default, reach for vector unless you have a concrete reason for a fixed array. The safety and convenience usually win.
Sizing and Initialization
int raw[4] = {1, 2, 3, 4};
std::vector<int> v1 = {1, 2, 3, 4};
std::vector<int> v2(4, 0); // four zeros
Remember that vector zero argument creation starts empty. A common mistake expects it to already hold a capacity of empty slots visible through size.
A Practical Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> readings;
readings.push_back(18);
readings.push_back(21);
readings.push_back(15);
int total = 0;
for (int value : readings) {
total += value;
}
double average = static_cast<double>(total) / readings.size();
std::cout << "Count: " << readings.size() << std::endl;
std::cout << "Average: " << average << std::endl;
return 0;
}
The program collects variable length input style data, then computes a summary without ever hard coding the count.
Common Mistakes
| Mistake | Result |
|---|---|
| Indexing an empty vector | Out of range access |
| Forgetting vector include | Compiler cannot find type |
| Assuming size stays fixed after clear | size becomes zero |
| Using raw array without length | Dangerous loops |
| Reserve confusion | capacity is not size |
Key Takeaways
💡
- Fixed arrays are simple but locked to one size
- vector grows dynamically and remembers its length
- Use at during learning to catch bad indexes early
- Prefer vector unless a constant size is required
- Always include the proper header for the container you use
Practice Questions
- Write a vector of five integers filled with a loop from 1 through 5.
- List three advantages of vector over a plain array.
- What does size return for a vector that never had push_back called?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions