vectors in stl cpp tutorial
vectors in stl cpp tutorial
Introduction
A vector in C++ is a part of the Standard Template Library (STL) and is one of the most commonly used sequence containers. It functions like a dynamic array that can grow or shrink in size at runtime. Unlike arrays, vectors automatically manage memory, making them more flexible and safer to use.
Dynamic resizing at runtime
Provides random access to elements (like arrays)
Automatically handles memory allocation and deallocation
Supports various built-in functions for insertion, deletion, and traversal
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers; // Empty vector
// Initializing with values
vector<int> nums = {10, 20, 30, 40};
// Adding elements
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
// Displaying elements
for (int n : nums) {
cout << n << " ";
}
return 0;
}
Function | Description |
---|---|
push_back() | Adds an element to the end of the vector |
pop_back() | Removes the last element |
size() | Returns the number of elements |
capacity() | Returns the current allocated storage |
at(index) | Access element at specified index safely |
front() | Returns the first element |
back() | Returns the last element |
clear() | Removes all elements |
empty() | Checks if the vector is empty |
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {5, 10, 15, 20};
cout << "Using index-based for loop: ";
for (size_t i = 0; i < nums.size(); i++) {
cout << nums[i] << " ";
}
cout << "\nUsing range-based for loop: ";
for (int n : nums) {
cout << n << " ";
}
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> names = {"Alice", "Bob", "Charlie"};
vector<string>::iterator it;
for (it = names.begin(); it != names.end(); ++it) {
cout << *it << " ";
}
return 0;
}
Easy to use and manage compared to arrays
Dynamic resizing capability
Provides rich set of built-in methods
Compatible with STL algorithms
Vectors are one of the most important and versatile containers in C++. They simplify dynamic memory handling and offer powerful functionalities to store and manipulate collections of data efficiently.