Arrays and Vectors
Most programs need to work with collections of values, not just single variables. C++ gives you two main options: fixed-size arrays and resizable vectors.
#include <iostream>
#include <vector>
int main() {
int scores[3] = {80, 92, 67}; // fixed-size array
std::cout << "first score: " << scores[0] << std::endl;
std::vector<int> xp = {10, 20, 30}; // resizable array
xp.push_back(40);
int total = 0;
for (int value : xp) {
total += value;
}
std::cout << "total xp: " << total << std::endl;
std::cout << "vector size: " << xp.size() << std::endl;
return 0;
}
Arrays vs. vectors
- A plain array (
int scores[3]) has a fixed size decided at compile time, it can never grow or shrink, and accessing an out-of-bounds index (likescores[5]) is undefined behavior, C++ won't stop you. std::vector<T>, part of the Standard Template Library (STL), is a resizable array,push_backadds an element,size()tells you how many there are.- The range-based
for (int value : xp)loop visits every element without needing an index, read it as "for each value in xp".
TIP
When you're not sure how many elements you'll need, reach for std::vector by default, plain arrays are mostly useful when the size is small and fixed ahead of time.