cpp / beginner
Snippet
Working with std::vector
std::vector is a dynamic array from the C++ Standard Library that can grow and shrink at runtime. It provides methods like push_back() to add elements, pop_back() to remove the last element, and size() to get the number of elements. It's 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
#include <iostream>#include <vector>int main() {std::vector<int> numbers = {10, 20, 30};numbers.push_back(40);std::cout << "Size: " << numbers.size() << std::endl;for (int i = 0; i < numbers.size(); i++) {std::cout << numbers[i] << " ";}std::cout << std::endl;numbers.pop_back();std::cout << "First element: " << numbers.front() << std::endl;std::cout << "Last element: " << numbers.back() << std::endl;return 0;}
Breakdown
1
std::vector<int> numbers = {10, 20, 30};
Creates a vector initialized with three integers
2
numbers.push_back(40);
Adds 40 to the end of the vector
3
numbers.front() and numbers.back()
Access first and last elements respectively
4
numbers.pop_back();
Removes the last element from the vector