Welcome to The Coding College! In this tutorial, we’ll explore the C++ <vector>
library, a powerful and flexible container in the Standard Template Library (STL) used for dynamic array management. Vectors provide an efficient way to store, access, and manipulate sequences of elements.
What is the <vector>
Library?
The <vector>
library in C++ allows you to create dynamic arrays that can automatically resize themselves when elements are added or removed. Unlike traditional arrays, vectors can change their size at runtime, making them ideal for scenarios where the size of the array is not known in advance.
To use the vector library, include it in your program:
#include <vector>
Features of Vectors
- Dynamic Sizing: Automatically resizes as elements are added or removed.
- Random Access: Supports direct access to elements using indices, similar to arrays.
- Standard Functions: Provides built-in methods for operations like insertion, deletion, and searching.
- Memory Management: Manages memory internally, freeing you from manual allocation and deallocation.
Basic Syntax
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myVector; // Declare a vector of integers
return 0;
}
Common Operations with Vectors
Operation | Functionality | Example |
---|---|---|
Add Element | push_back() adds an element to the end of the vector. | myVector.push_back(10); |
Access Element | Use [index] or at(index) to access elements. | myVector[0] or myVector.at(0); |
Remove Last Element | pop_back() removes the last element. | myVector.pop_back(); |
Size | size() returns the number of elements in the vector. | myVector.size(); |
Insert Element | insert() adds an element at a specific position. | myVector.insert(myVector.begin(), 5); |
Remove Element | erase() removes an element or a range of elements. | myVector.erase(myVector.begin()); |
Clear | clear() removes all elements from the vector. | myVector.clear(); |
Check if Empty | empty() checks if the vector is empty. | myVector.empty(); |
Example: Vector Basics
Here’s a simple example demonstrating vector usage:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myVector;
// Adding elements
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
// Accessing elements
cout << "First element: " << myVector[0] << endl;
// Removing last element
myVector.pop_back();
// Iterating through the vector
cout << "Vector elements: ";
for (int val : myVector) {
cout << val << " ";
}
return 0;
}
Output:
First element: 10
Vector elements: 10 20
Useful Member Functions
1. Adding Elements: push_back()
myVector.push_back(15); // Adds 15 to the end of the vector
2. Accessing Elements: at()
vs []
at()
performs bounds checking, while[]
does not.
cout << myVector.at(1); // Safe access
cout << myVector[1]; // Direct access
3. Removing Elements: erase()
and clear()
myVector.erase(myVector.begin() + 1); // Removes the second element
myVector.clear(); // Removes all elements
4. Inserting Elements: insert()
myVector.insert(myVector.begin() + 1, 25); // Inserts 25 at the second position
Advanced Operations
1. Sorting a Vector
You can sort a vector using the <algorithm>
library:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> numbers = {30, 10, 50, 20, 40};
// Sort in ascending order
sort(numbers.begin(), numbers.end());
cout << "Sorted numbers: ";
for (int num : numbers) {
cout << num << " ";
}
return 0;
}
Output:
Sorted numbers: 10 20 30 40 50
2. Two-Dimensional Vectors
Vectors can store other vectors to create multi-dimensional arrays.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access element
cout << "Element at (1,1): " << matrix[1][1] << endl;
return 0;
}
Output:
Element at (1,1): 5
Advantages of Vectors
- Dynamic Sizing: No need to define the size beforehand.
- Rich Functionality: Provides a range of built-in functions for manipulation.
- Safety: Bounds checking with
at()
method.
Limitations of Vectors
- Overhead: Memory reallocation can be expensive when resizing frequently.
- Performance: Slower than raw arrays in some performance-critical applications.
Summary
The <vector>
library is one of the most versatile and commonly used containers in C++. Its dynamic nature and rich feature set make it ideal for a wide range of applications, from basic programming tasks to complex data manipulation.
For more tutorials, visit The Coding College. Let’s code smarter, together! 🚀