Quick Answer
Master the std::vector container.
Understanding the Issue
Vectors are dynamic arrays that provide random access and automatic resizing. They are the most commonly used STL container.
The Problem
This code demonstrates the issue:
Cpp
Error
// Need a resizable array of integers
The Solution
Here's the corrected code:
Cpp
Fixed
#include <vector>
#include <algorithm>
int main() {
// Create and populate
std::vector<int> numbers = {7, 3, 5, 1};
// Add elements
numbers.push_back(9);
// Access elements
int first = numbers[0];
int last = numbers.back();
// Sort
std::sort(numbers.begin(), numbers.end());
// Range-based for loop (C++11)
for (int num : numbers) {
std::cout << num << " ";
}
// Output: 1 3 5 7 9
return 0;
}
Key Takeaways
Vectors combine array performance with dynamic resizing.