C++ Vectors

Welcome to The Coding College! In this tutorial, we will explore vectors in C++, one of the most versatile and widely used data structures provided by the Standard Template Library (STL).

What Are Vectors in C++?

A vector is a dynamic array that can resize itself automatically when elements are added or removed. Unlike regular arrays, vectors offer several useful member functions to manage data efficiently.

Key Features of Vectors:

  • Dynamic size: Automatically adjusts its size to accommodate elements.
  • Efficient access: Provides fast element access using indices.
  • Versatile operations: Includes built-in functions like push_back, pop_back, and more.

Declaring a Vector

You need to include the <vector> header to use vectors.

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers; // Declare an empty vector of integers
    vector<string> words = {"Hello", "World"}; // Vector with initial values

    return 0;
}

Adding Elements to a Vector

You can add elements to the end of a vector using the push_back method.

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers;

    numbers.push_back(10); // Add 10 to the vector
    numbers.push_back(20); // Add 20 to the vector
    numbers.push_back(30); // Add 30 to the vector

    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

Output:

10 20 30  

Accessing Vector Elements

You can access elements in a vector using an index (just like arrays).

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    cout << "First element: " << numbers[0] << endl;  
    cout << "Second element: " << numbers[1] << endl;  

    return 0;
}

Output:

First element: 10  
Second element: 20  

Common Vector Operations

1. Size and Capacity

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    cout << "Size: " << numbers.size() << endl;  
    cout << "Capacity: " << numbers.capacity() << endl;

    return 0;
}

Output:

Size: 3  
Capacity: 3  

2. Remove Elements with pop_back

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    numbers.pop_back(); // Removes the last element

    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

Output:

10 20  

3. Insert Elements

You can insert an element at any position using insert.

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    numbers.insert(numbers.begin() + 1, 15); // Insert 15 at position 1

    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

Output:

10 15 20 30  

4. Remove Elements with erase

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    numbers.erase(numbers.begin() + 1); // Removes the element at position 1

    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

Output:

10 30  

5. Clear the Vector

The clear function removes all elements from the vector.

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    numbers.clear(); // Clear the vector

    cout << "Size after clearing: " << numbers.size() << endl;

    return 0;
}

Output:

Size after clearing: 0  

Iterating Over a Vector

You can use a range-based for loop or an iterator to iterate over a vector.

Using Range-Based For Loop

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

Using Iterators

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    for (vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
        cout << *it << " ";
    }

    return 0;
}

Multi-Dimensional Vectors

Vectors can also store other vectors, creating multi-dimensional structures.

#include <vector>  
#include <iostream>  
using namespace std;

int main() {
    vector<vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    for (const auto& row : matrix) {
        for (int num : row) {
            cout << num << " ";
        }
        cout << endl;
    }

    return 0;
}

Output:

1 2 3  
4 5 6  
7 8 9  

Real-World Applications of Vectors

  1. Dynamic Arrays: Replace traditional arrays for flexible storage.
  2. 2D Grids: Create multi-dimensional vectors for simulations or games.
  3. Custom Data Handling: Store and manipulate user-defined types.

Summary

  • Advantages: Vectors are dynamic, versatile, and efficient for most use cases.
  • Common Functions: Use push_back, pop_back, insert, erase, clear, etc.
  • Iterators: Provide flexibility for traversing and manipulating vectors.

Learn More at The Coding College

For more tutorials on C++ and modern programming practices, visit The Coding College.

Leave a Comment