Vector

Programming

std::vector is a dynamic array container from the C++ Standard Library that automatically manages memory and can grow and shrink in size. It is one of the most commonly used containers in modern C++.

Basic Usage

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    numbers.push_back(6); // Add an element
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}

Common Operations

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec;
    
    // Adding elements
    vec.push_back(10);
    vec.push_back(20);
    vec.push_back(30);
    
    // Accessing elements
    std::cout << "First element: " << vec[0] << std::endl;
    std::cout << "Size: " << vec.size() << std::endl;
    std::cout << "Capacity: " << vec.capacity() << std::endl;
    
    // Safe access with bounds checking
    if (!vec.empty()) {
        std::cout << "Last element: " << vec.back() << std::endl;
    }
    
    // Inserting at specific position
    vec.insert(vec.begin() + 1, 15);
    
    // Removing elements
    vec.pop_back();
    
    // Iterating
    for (size_t i = 0; i < vec.size(); ++i) {
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

Initialization Methods

#include <vector>

int main() {
    // Empty vector
    std::vector<int> vec1;
    
    // With initial size
    std::vector<int> vec2(5);  // 5 elements, all zero-initialized
    
    // With initial size and value
    std::vector<int> vec3(5, 10);  // 5 elements, all set to 10
    
    // From initializer list
    std::vector<int> vec4 = {1, 2, 3, 4, 5};
    
    // From another vector (copy)
    std::vector<int> vec5(vec4);
    
    // From range
    std::vector<int> vec6(vec4.begin(), vec4.begin() + 3);
    
    return 0;
}

Performance Considerations

Best Practices

Common Pitfalls

Advantages over C-style Arrays

Output

1 2 3 4 5 6