The std::vector is a dynamic array provided by C++ STL. It supports many methods to manage its elements efficiently. Below, we explain each key method with a definition and example code snippet.
🔧 Vector Methods Explained
1. assign(start, end)
Definition: Copies elements from a given range defined by iterators start and end into the vector, replacing its contents.
vector<int> v1 = {10, 20, 30};
vector<int> v2;
v2.assign(v1.begin(), v1.end()); // v2 now contains {10, 20, 30}
2. at(index)
Definition: Returns the element at the specified index. It performs bounds checking and throws an exception if out of range.
int value = v2.at(1); // Returns 20, the element at index 1
3. back()
Definition: Returns a reference to the last element in the vector.
int last = v2.back(); // Returns 30
4. begin()
Definition: Returns an iterator pointing to the first element of the vector.
auto it = v2.begin(); cout << *it; // Outputs 10, the first element
5. capacity()
Definition: Returns the current allocated storage capacity of the vector (how many elements it can hold without reallocating memory).
cout << "Capacity: " << v2.capacity() << endl;
6. clear()
Definition: Removes all elements from the vector, making it empty but does not reduce capacity.
v2.clear(); // Now v2 is empty
7. empty()
Definition: Returns true if the vector has no elements, otherwise false.
if (v2.empty()) {
cout << "v2 is empty" << endl;
}
8. end()
Definition: Returns an iterator pointing one past the last element of the vector. Used for iteration limits.
auto itEnd = v1.end();
9. erase(iterator position)
Definition: Removes the element at the specified position and shifts all elements after it forward.
v1.erase(v1.begin() + 1); // Removes element at index 1 (20)
// v1 now: {10, 30}
10. front()
Definition: Returns a reference to the first element in the vector.
int first = v1.front(); // Returns 10
11. insert(iterator position, value)
Definition: Inserts the given value at the specified position, shifting subsequent elements right.
v1.insert(v1.begin() + 1, 25); // Inserts 25 at index 1
// v1 now: {10, 25, 30}
12. pop_back()
Definition: Removes the last element from the vector, reducing its size by one.
v1.pop_back(); // Removes 30
// v1 now: {10, 25}
13. push_back()
Definition: Adds a new element to the end of the vector, increasing its size by one.
v1.push_back(40); // v1 now: {10, 25, 40}
14. size()
Definition: Returns the number of elements currently stored in the vector.
cout << "Size: " << v1.size() << endl; // Outputs: 3