<vector>
The <vector>
header provides the std::vector
container, which is a dynamic array that can grow or shrink in size. It's one of the most commonly used containers in C++ due to its flexibility and efficiency for many tasks.
std::vector<T>
: The main container class, where T is the element type#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
numbers.push_back(6); // Add element to the end
std::cout << "Size: " << numbers.size() << std::endl;
std::cout << "Capacity: " << numbers.capacity() << std::endl;
// Accessing elements
std::cout << "First element: " << numbers[0] << std::endl;
std::cout << "Last element: " << numbers.back() << std::endl;
// Iterating
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
std::vector
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
// Reserve space for 10 elements
vec.reserve(10);
std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl;
// Add 5 elements
for (int i = 0; i < 5; ++i) {
vec.push_back(i);
}
std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl;
// Resize to 7 elements
vec.resize(7);
std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl;
// Shrink to fit
vec.shrink_to_fit();
std::cout << "Size: " << vec.size() << ", Capacity: " << vec.capacity() << std::endl;
return 0;
}
reserve()
to pre-allocate memoryresize()
affects the vector's sizeshrink_to_fit()
to reduce unused capacity#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {5, 2, 8, 1, 9};
// Sorting
std::sort(vec.begin(), vec.end());
// Finding an element
auto it = std::find(vec.begin(), vec.end(), 8);
if (it != vec.end()) {
std::cout << "Found 8 at position: " << std::distance(vec.begin(), it) << std::endl;
}
// Removing elements
vec.erase(std::remove_if(vec.begin(), vec.end(),
[](int n) { return n % 2 == 0; }),
vec.end());
std::cout << "After removing even numbers: ";
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
sort
, find
, and remove_if
reserve()
when size is knownvector<bool>
is a specialized template that optimizes for spacestd::vector
is a versatile and efficient container that provides dynamic array functionality in C++. It's widely used due to its flexibility and performance characteristics.
reserve()
By using std::vector
, C++ developers can manage collections of elements with ease, benefiting from both dynamic sizing and the performance of contiguous memory storage. It's often the go-to container for sequences of elements when the size isn't known at compile time or needs to change during runtime.