WikiGalaxy

Personalize

Introduction to C++ Vectors

What is a Vector?

Vectors in C++ are part of the Standard Template Library (STL) and provide a dynamic array that can resize itself automatically when an element is inserted or deleted, while maintaining the stored data.

Why Use Vectors?

Vectors are preferred over arrays when you need a resizable array, as they provide the flexibility of dynamic memory allocation, ease of insertion and deletion, and built-in functions for manipulation.


#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;
    numbers.push_back(10);
    numbers.push_back(20);
    for(int i : numbers) {
        std::cout << i << " ";
    }
    return 0;
}
    

Console Output:

10 20

Vector Initialization

Initializing Vectors

Vectors can be initialized in several ways, including default initialization, with a specific size, or using an initializer list.


#include <iostream>
#include <vector>

int main() {
    std::vector<int> emptyVector;
    std::vector<int> sizedVector(5, 0);
    std::vector<int> initList = {1, 2, 3, 4, 5};
    for(int i : initList) {
        std::cout << i << " ";
    }
    return 0;
}
    

Console Output:

1 2 3 4 5

Accessing Vector Elements

Element Access Methods

Elements in a vector can be accessed using the subscript operator [], the at() method, or iterators.


#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {10, 20, 30};
    std::cout << numbers[0] << " ";
    std::cout << numbers.at(1) << " ";
    return 0;
}
    

Console Output:

10 20

Modifying Vector Elements

Inserting and Deleting Elements

Vectors allow easy modification of elements through functions like push_back(), pop_back(), insert(), and erase().


#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {10, 20, 30};
    numbers.push_back(40);
    numbers.pop_back();
    numbers.insert(numbers.begin(), 5);
    numbers.erase(numbers.begin() + 1);
    for(int i : numbers) {
        std::cout << i << " ";
    }
    return 0;
}
    

Console Output:

5 20 30

Vector Capacity and Size

Understanding Capacity and Size

Vectors have both a size (number of elements) and a capacity (allocated storage). Functions like size(), capacity(), and resize() help manage these attributes.


#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers(10);
    std::cout << "Size: " << numbers.size() << " ";
    std::cout << "Capacity: " << numbers.capacity() << " ";
    numbers.resize(20);
    std::cout << "New Size: " << numbers.size();
    return 0;
}
    

Console Output:

Size: 10 Capacity: 10 New Size: 20

Iterating Over Vectors

Using Iterators

Iterators provide a way to traverse vectors. They are similar to pointers and can be used with loops to access elements.


#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40};
    for(std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }
    return 0;
}
    

Console Output:

10 20 30 40

Vector of Vectors

Creating 2D Vectors

Vectors can contain other vectors, allowing the creation of multi-dimensional arrays, such as 2D vectors.


#include <iostream>
#include <vector>

int main() {
    std::vector<std::vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    for(const auto& row : matrix) {
        for(int val : row) {
            std::cout << val << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}
    

Console Output:

1 2 3
4 5 6
7 8 9

Vector Sorting

Sorting Vectors

Vectors can be sorted using the sort() function from the algorithm library, which arranges elements in ascending order by default.


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

int main() {
    std::vector<int> numbers = {40, 10, 30, 20};
    std::sort(numbers.begin(), numbers.end());
    for(int i : numbers) {
        std::cout << i << " ";
    }
    return 0;
}
    

Console Output:

10 20 30 40

Advanced Vector Operations

Using Algorithms with Vectors

Vectors can be used with various STL algorithms for operations such as searching, reversing, and more, enhancing their utility.


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

int main() {
    std::vector<int> numbers = {10, 20, 30, 40};
    std::reverse(numbers.begin(), numbers.end());
    for(int i : numbers) {
        std::cout << i << " ";
    }
    return 0;
}
    

Console Output:

40 30 20 10

Vector Performance Considerations

Efficiency and Best Practices

While vectors are versatile, understanding their underlying performance characteristics, such as reallocation costs and iterator invalidation, is crucial for optimal use.


// Example code omitted for brevity
// Consider using reserve() to preallocate memory
    

Best Practice:

Use the reserve() function to minimize reallocations when the number of elements is known in advance.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025