#include <vector>
Declaration
std::vector<Type> vec_name;
Insertion
vec_name.push_back(value); // Add to end
vec_name.insert(vec_name.begin() + index, value); // Insert at position
Access Element
Type val = vec_name[index]; // Direct access
Type val = vec_name.at(index); // Bounds-checked access
Check if Empty
if (vec_name.empty()) {
// Vector is empty
}
Erase Element
vec_name.erase(vec_name.begin() + index); // Remove at index
vec_name.clear(); // Remove all elements
Iterate Through Elements
for (const auto& val : vec_name) {
std::cout << val << std::endl;
}
In reverse order:
for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
std::cout << *it << " ";
}
Reverse the order of a Vector
std::reverse(vec.begin(), vec.end());
Size and Capacity
vec_name.size(); // Number of elements
vec_name.capacity(); // Allocated storage capacity
vec_name.resize(new_size); // Resize vector
Other Useful Functions
vec_name.front(); // First element
vec_name.back(); // Last element
vec_name.pop_back(); // Remove last element
10. Check if Element Exists
#include <algorithm>
if (std::find(vec_name.begin(), vec_name.end(), value) != vec_name.end()) {
// Element found
} else {
// Element not found
}
11. Ways to Construct a Vector
// Empty vector
std::vector<int> v1;
// Vector with 5 default-initialized ints (0)
std::vector<int> v2(5);
// Vector with 5 elements, each initialized to 42
std::vector<int> v3(5, 42);
// Copy constructor
std::vector<int> v4 = v3;
// Move constructor
std::vector<int> v5 = std::move(v3);
// Construct from initializer list
std::vector<int> v6 = {1, 2, 3, 4, 5};
// Construct from array
int arr[] = {10, 20, 30};
std::vector<int> v7(std::begin(arr), std::end(arr));
// Construct from iterators
std::vector<int> source = {5, 6, 7};
std::vector<int> v8(source.begin(), source.end());