Arrays in C++ cannot be extended or shrunk. This means that no matter what you do, you cannot add or remove elements from it without just recreating the whole array.
int arr[] = {3, 5, 56, 12, 9};
Due to this, 90% of use cases are better solved with vectors, at least for humans coding. Arrays still have their uses in the backend for uses that you may never see. For example, the string
type is actually an array of char
types, like such:
char s[] = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
However, while the length of an array may not change, the elements inside it can by using an index.
arr[0] = 7; arr[2] = 79; arr[3] = 54; int arr[] = {37, 5, 5679, 1254, 9};
Vectors in C++ behave almost the exact same as arrays but with the crucial difference that they can have elements added and taken away.
vector<int> v; v.push_back(5); v.push_back(24); v.push_back(12); vector<int& v = {5, 24, 12};
Vectors also have many more functions associated with them, such as the push_back()
shown above that adds an element to the end of a vector, pop_back()
to remove the element at the end of a vector, and size()
to give exactly how many elements there are.
v.size(); vector<int> v = { 5, //1 24, //2 12 //3 }; // Returns 3
For loops are a control flow function allowing you to repeat a line of code for a certain number of times, such as this one which repeats 3 times.
for (int i = 0; i < 3; i++) { write_line("Hello, World!"); }
// Returns > Hello, World! > Hello, World! > Hello, World!
However their main use is to iterate through data so you don't have to re-use code and can be more flexible with your data, such as being able to work through every element in a vector, no matter the size.
vector<string> v = {"Hello,", "World", "!"} for (int i = 0; i < v.size(); i++) { write_line(v[i]); }
// Returns > Hello, > World > !