C++ std::vector Functions - Complete Notes
Introduction to vector
- std::vector is a dynamic array provided by the C++ Standard Template Library (STL).
- It can grow or shrink in size and allows random access to elements.
Header file:
#include <vector>
Namespace:
using namespace std;
1. Constructor Functions
- vector<T> v; -> Creates an empty vector of type T.
- vector<T> v(n); -> Creates a vector with n default-initialized elements.
- vector<T> v(n, val); -> Creates a vector with n elements, each of value val.
- vector<T> v1(v2); -> Copy constructor.
- vector<T> v1(v2.begin(), v2.end());-> Range constructor.
2. Capacity Functions
- v.size() -> Number of elements in the vector.
- v.capacity() -> Allocated storage size.
- v.max_size() -> Max possible elements.
- v.empty() -> Checks if vector is empty.
- v.resize(n) -> Resizes vector to n elements.
- v.resize(n, val) -> Resizes and fills new with val.
- v.shrink_to_fit() -> Reduces capacity to size.
- v.reserve(n) -> Reserves storage.
3. Element Access Functions
- v[i] -> Direct access (no check).
- v.at(i) -> Access with bounds check.
- v.front() -> First element.
- v.back() -> Last element.
- v.data() -> Pointer to array.
4. Modifiers
- v.push_back(val) -> Add val at end.
- v.pop_back() -> Remove last.
- v.insert(pos, val) -> Insert before pos.
- v.insert(pos, n, val)-> Insert val n times.
- v.erase(pos) -> Remove at pos.
- v.erase(start, end) -> Remove range.
- v.clear() -> Remove all.
- v.swap(v2) -> Swap with v2.
- v.assign(n, val) -> Assign n copies.
- v.assign(start, end) -> Assign from range.
- v.emplace(pos, val) -> Faster insert.
- v.emplace_back(val) -> Faster push_back.
5. Iterators
- v.begin(), v.end()
- v.rbegin(), v.rend()
- v.cbegin(), v.cend()
- v.crbegin(), v.crend()
6. Relational Operators
- v1 == v2, v1 != v2, v1 < v2, v1 > v2, v1 <= v2, v1 >= v2
7. Utility Functions
- std::swap(v1, v2)
- std::sort(v.begin(), v.end())
Example Code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {10, 20, 30};
v.push_back(40);
v.insert(v.begin() + 1, 15);
v.pop_back();
cout << "Size: " << v.size() << endl;
cout << "First Element: " << v.front() << endl;
cout << "Last Element: " << v.back() << endl;
for (int x : v)
cout << x << " ";
return 0;