
Mastering C++ Vectors: A Deep Dive into Essential Operations
In C++, vector is one of the most powerful and commonly used Standard Template Library (STL) containers. It provides dynamic resizing, meaning it can grow and shrink as needed, making it incredibly useful when you don’t know the exact number of elements you'll need ahead of time.
In this blog, we’ll walk you through the core functions you can use with a vector and demonstrate them with Indian cricketers' names. From adding new elements to removing them, resizing, and even iterating, vectors offer a wide range of functionalities.
Common Functions for Vectors
A vector behaves like an array but with dynamic size management. C++ provides a rich set of functions to make vector manipulation seamless. Let’s explore the most common operations you can perform with vectors:
1. Basic Operations
1.1 push_back(value)
Adds an element to the end of the vector.
vector<int> v; v.push_back(10); // Adds 10 to the end v.push_back(20); // Adds 20 to the end
1.2 pop_back()
Removes the last element from the vector.
v.pop_back(); // Removes the last element (20)
1.3 insert(position, value)
Inserts an element at a specific position in the vector.
v.insert(v.begin() + 1, 15); // Inserts 15 at position 1
1.4 erase(position)
Removes the element at the specified position.
v.erase(v.begin() + 1); // Removes element at position 1 (15)
1.5 clear()
Removes all elements from the vector.
v.clear(); // Removes all elements
1.6 resize(new_size)
Resizes the vector to the specified size. If the new size is larger, new elements are initialized with 0 (or default values).
v.resize(5); // Resizes the vector to contain 5 elements
1.7 reserve(n)
Reserves space for at least n elements. This is useful for improving performance when you know the number of elements you’ll need in advance.
v.reserve(10); // Reserves space for 10 elements
2. Accessing Elements
2.1 size()
Returns the number of elements currently stored in the vector.
int n = v.size(); // Number of elements in the vector
2.2 capacity()
Returns the current capacity of the vector (i.e., how much space it can hold).
int cap = v.capacity(); // Returns the allocated space size
2.3 empty()
Checks whether the vector is empty.
bool isEmpty = v.empty(); // Returns true if vector is empty
2.4 at(index)
Accesses the element at the given index with bounds checking. If the index is out of range, it throws an exception.
int value = v.at(1); // Accesses the second element
2.5 [] operator
Accesses an element directly at the given index without bounds checking.
int value = v[1]; // Accesses the second element
2.6 front()
Returns the first element of the vector.
int firstElement = v.front(); // Accesses the first element
2.7 back()
Returns the last element of the vector.
int lastElement = v.back(); // Accesses the last element
3. Iterators for Traversing Vectors
Vectors support iterators for traversing elements. You can iterate forward or backward through the vector using the following functions:
3.1 begin()
Returns an iterator pointing to the first element.
auto it = v.begin(); // Points to the first element
3.2 end()
Returns an iterator just past the last element.
auto it = v.end(); // Points past the last element
3.3 rbegin()
Returns a reverse iterator pointing to the last element.
auto rit = v.rbegin(); // Points to the last element
3.4 rend()
Returns a reverse iterator pointing before the first element.
auto rit = v.rend(); // Points before the first element
4. Other Useful Functions
4.1 swap(other_vector)
Swaps the contents of the current vector with another vector.
vector<int> v2 = {1, 2, 3}; v.swap(v2); // Swaps the contents of v with v2
4.2 assign(n, value)
Assigns n copies of value to the vector.
v.assign(5, 10); // Assigns 5 copies of 10 to the vector
4.3 resize(new_size, value)
Resizes the vector to the specified size. If the size is increased, new elements are initialized with value.
v.resize(8, 100); // Resizes the vector to 8 elements, with 100 as the new values
4.4 emplace_back(value)
Constructs an element in place at the end of the vector. This is more efficient than push_back() for complex types.
v.emplace_back(30); // Constructs 30 at the end of the vector
4.5 emplace(position, value)
Constructs an element in place at the specified position.
v.emplace(v.begin() + 1, 25); // Constructs 25 at position 1
Real-Life Example: Working with Indian Cricketers
Let’s put these functions into practice by using a vector to manage a list of Indian cricketers.
Code Example:
#include <iostream> #include <vector> using namespace std; int main() { // Step 1: Initialize vector with cricketers vector<string> cricketers = {"Virat Kohli", "Rohit Sharma", "MS Dhoni"}; // Step 2: Add a new cricketer at the end cricketers.push_back("Jasprit Bumrah"); // Step 3: Remove a cricketer (remove last element) cricketers.pop_back(); // Step 4: Insert a cricketer at a specific position cricketers.insert(cricketers.begin() + 1, "KL Rahul"); // Step 5: Resize the vector cricketers.resize(5, "Hardik Pandya"); // Fill remaining with "Hardik Pandya" // Step 6: Display all cricketers cout << "Cricketers in the Team:\n"; for (const string& name : cricketers) { cout << name << "\n"; } return 0; }
Output:
Cricketers in the Team: Virat Kohli KL Rahul Rohit Sharma MS Dhoni Hardik Pandya
What Happened:
- push_back: Added Jasprit Bumrah at the end.
- pop_back: Removed Jasprit Bumrah.
- insert: Added KL Rahul at position 1.
- resize: Increased the size and filled remaining slots with Hardik Pandya.
Performance Considerations
Here’s a quick overview of how vector operations perform:
- push_back() is typically O(1), but can occasionally be O(n) when the vector needs to resize.
- insert() and erase() are O(n) due to element shifting.
- resize() can also be O(n) when resizing to a larger size.
Final Thoughts
Vectors are incredibly flexible and efficient, making them one of the most widely used containers in C++. With these functions in your toolkit, you can manage dynamic data collections with ease, whether you're keeping track of cricketers, processing game scores, or handling real-time data in your applications.
0 Comments