cpp / beginner
Snippet
The Standard Library Vector: Dynamic Arrays
A vector is a dynamic array from the Standard Library that can grow or shrink at runtime. Unlike fixed-size arrays, vectors allow you to add elements using push_back(). The size() method returns the current number of elements.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>#include <vector>using namespace std;int main() {vector<int> numbers;numbers.push_back(10);numbers.push_back(20);numbers.push_back(30);for (int i = 0; i < numbers.size(); i++) {cout << numbers[i] << endl;}return 0;}
Breakdown
1
vector<int> numbers;
Declares a vector that holds integer values
2
numbers.push_back(10);
Adds an element to the end of the vector
3
numbers.size()
Returns the number of elements in the vector