cpp / beginner
Snippet
Vectors: Dynamic Arrays Made Easy
Vectors are smart arrays from the C++ Standard Library that can grow and shrink dynamically. Unlike regular arrays, you don't need to know the size upfront. Use push_back() to add elements, pop_back() to remove the last element, and size() to get the current number of elements. Vectors are safer and more flexible than raw arrays.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>#include <vector>using namespace std;int main() {vector<int> scores;scores.push_back(85);scores.push_back(92);scores.push_back(78);vector<string> names = {"Anna", "Ben", "Clara"};cout << "Erste Punktzahl: " << scores[0] << endl;cout << "Anzahl der Namen: " << names.size() << endl;scores.pop_back();cout << "Neue Größe: " << scores.size() << endl;for (int i = 0; i < names.size(); i++) {cout << names[i] << endl;}return 0;}
Breakdown
1
vector<int> scores;
Declares an empty vector that will hold integers
2
push_back(85);
Appends the value 85 to the end of the vector
3
names.size()
Returns the number of elements in the vector
4
pop_back();
Removes the last element from the vector