Open In App

When to Use Vector Instead of Array in C++?

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, both arrays and vectors are used to store collections of data. Arrays are a basic fixed-size sequence of elements, whereas vectors are part of the C++ STL and offer dynamic sizing and more flexibility. There are some cases where using vectors can be more beneficial than using arrays. In this article, we will learn when to use vectors instead of arrays in C++.

When to Use Vector Instead of Array in C++?

Choosing between an array and std::vector depends on specific requirements such as the size of the collection, performance considerations, and ease of use. Following are the cases where using vectors in place of arrays is more advantageous:

1. Dynamic Size

Unlike arrays, vectors in C++ are dynamic, meaning their size can change during runtime which is useful when the number of elements is not known in advance.

Example:

The below example demonstrates the dynamic nature of vectors in C++.

C++
// C++ Program to represent the dynamic nature of a vector
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int>
        dynamicVec; // Size not known at compile time

    // Adding elements
    for (int i = 0; i < 10; ++i) {
        dynamicVec.push_back(i * i);
    }
    cout << "Vector size after additions: "
         << dynamicVec.size() << endl;

    // Removing an element
    dynamicVec.pop_back();

    // printing size of dynamicVec after removal of element
    cout << "Vector size after removal: "
         << dynamicVec.size() << endl;

    return 0;
}

Output
Vector size after additions: 10
Vector size after removal: 9

2. Ease of Insertion and Deletion

The std::vector provides a bunch of methods like vector::push_ back(), vector:pop_back(), vector::insert(), vector::erase() which make it easy to insert and delete elements. Arrays do not have built-in functions for these operations.

Example:

The below example demonstrates the ease of performing insertion and deletion in vectors in C++.

C++
// C++ Program to demonstrate efficient insertion and
// deletion operations in a vector
#include <iostream>
#include <vector>
using namespace std;

int main()
{

    // creating a vector of integers
    vector<int> vec = { 1, 2, 3, 4, 5 };

    // Adding an element
    vec.push_back(6);

    // Removing the last element
    vec.pop_back();

    vec.erase(vec.begin()); // Deleting an element

    // Accessing elements
    for (auto num : vec) {
        cout << num << " ";
    }
    return 0;
}

Output
2 3 4 5 

3. Return Vector From a Function

If we want to return an array as a return value from a function we can’t do it unless the array is dynamically allocated. However, we can easily return vectors as a return type from a function.

Example:

The below example demonstrates how we can a vector from a function in C++.

C++
// C++ Program to return vector from a function
#include <iostream>
#include <vector>
using namespace std;

// Function to return vector as a result
vector<int> createVector(int size)
{
    // Initialize a vector
    vector<int> result;
    for (int i = 0; i < size; ++i) {
        // Add squared values to the vector
        result.push_back(i * i);
    }
    // Return the vector
    return result;
}
int main()
{
    // Store the vector returned from the function
    vector<int> vec = createVector(5);

    // Print the elements of the result vector
    cout << "Vector elements: ";
    for (int num : vec) {
        cout << num << " ";
    }
    return 0;
}

4. STL Compatibility

Vectors are compatible with the STL and there are many STL algorithms and functions that work seamlessly with vectors but not with arrays.

Example:

The below example demonstrate the use of STL function in vector in C++.

C++
// C++ program to use STL in Vector
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{

    // creating a vector
    vector<int> vec = { 1, 3, 2, 5, 4 };

    // Sorting a vector using STL
    sort(vec.begin(), vec.end());

    // printing sorted vector
    cout << "Sorted Vector: ";
    for (auto num : vec) {
        cout << num << " ";
    }
    return 0;
}

Output
Sorted Vector: 1 2 3 4 5 

5. Safety and Convenience

Vectors are safer to use than arrays because they automatically manage memory and ensure that elements are contiguous in memory, similar to arrays. They also handle copying and assignment, reducing the risk of memory leaks and dangling pointers. Whereas managing dynamic arrays (e.g., allocated with new[]) requires manual deallocation with delete[], which can lead to memory management errors.

Conclusion 

In conclusion, while arrays are a fundamental part of C++, vectors provide a more flexible and convenient way to handle collections, especially when the size is not known in advance, or when elements need to be inserted or deleted. Vectors also offer better compatibility with the STL and are safer to use than arrays.





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads