How To Convert Array To Vector In C++

The  versatile nature of C++ makes it a programming language that has gained immense popularity among developers across various domains. This highly expressive language offers a rich assortment of features and data structures, including arrays and vectors.

While arrays are fixed in size and require manual memory management, vectors offer dynamic resizing and automatic memory management. Although arrays and vectors can both store multiple elements of the same data type, the unique properties and functionalities.

In this blog, we will explore different approaches and sample problems as well.So, let’s start the journey and gain some knowledge.

Why is converting an array to vector in c++ is needed?

There is the reasons why Converting an array to a vector in C++ is needed:

  1. Memory management: Vectors automatically manage memory, whereas arrays require manual memory management. Converting an array to a vector simplifies memory management and can help prevent memory leaks.
  1. Compatibility: Some libraries and functions in C++ may require the use of vectors instead of arrays. Converting an array to a vector can make your code more compatible with other libraries and functions.
  1. Dynamic resizing: Unlike arrays, vectors can dynamically resize themselves as new elements are added, making them a more flexible data structure.

How To Convert Array To Vector In C++

Here are six different approaches to how to convert array to vector in C++ with detailed solution steps, code, and output for each approach:

  1. Using the vector constructor
  2. Using the insert function
  3. Using the vector assign function
  4. Using the vector resize function
  5. Using the copy function
  6. Using the initializer list constructor

Let’s dive in more with examples to each approach.

Approach 1: Using the vector constructor

In C++, if you desire to transform an array into a vector, a potential solution is utilizing the vector constructor that takes two iterators as arguments. It’s worth noting that this constructor necessitates two parameters, specifically the initiatory and final iterators of the array.

Pros:

  • Simple and efficient approach
  • No need to loop through the array or vector explicitly
  • Preserves the order of elements in the array

Cons:

  • Requires knowledge of iterators and their usage
  • Cannot be used if the array size is unknown at compile time
  • If the vector constructor is used incorrectly, it may lead to undefined behavior

Code:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int arr[] = { 1, 2, 3, 4, 5 }; // Example array
    int n = sizeof(arr) / sizeof(arr[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<int> vec(arr, arr + n); // Using the vector constructor

    // Printing the vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }

    return 0;
}

Output:

1 2 3 4 5

Code Explanation:

  1. Define an integer array arr with some values and n to store the number of elements in the array.
  2. Create a vector vec using the vector constructor, passing in the arr and n as the beginning and end iterators. This initializes the vector with the elements of the array.
  3. Use a for loop to iterate over the vector and print its elements to the console.
  4. Return 0 to indicate successful execution of the program.

Approach 2: Using the insert function

One potential approach to converting an array into a vector is to use the insert function within the vector class. To execute this approach, one must traverse through the array and invoke the insert function to incorporate each of its elements into the vector.

Pros:

  • Can be used for arrays of any size, even at runtime
  • Allows you to modify the vector as you insert elements
  • Provides more control over the insertion process than other methods

Cons:

  • Requires explicit looping through the array and vector
  • May be slower than other approaches for large arrays
  • Cannot preserve the order of elements if the insert function is not used correctly

Code:

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

int main() {
    int arr[] = { 11,12,13,14,15 }; // Example array
    int n = sizeof(arr) / sizeof(arr[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<int> vec;

    for (int i = 0; i < n; i++) {
        vec.insert(vec.end(), arr[i]); // Using the insert function
    }

    // Printing the vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    return 0;
}

Output:

11 12 13 14 15 

Code Explanation:

  1. The code creates an array of integers called “arr” with 5 elements.
  2. The code creates an empty vector of integers called “vec”.
  3. Finally, the code loops through each element in the vector and prints it to the console, separated by spaces.

Approach 3: Using the vector assign function

One can opt for the use of the assign function of the vector class to seamlessly convert an array into a vector. This function mandates two iterators to be used as input arguments, whereby one can effortlessly pass the beginning and end iterators of the array to create a vector with the same elements.

Pros:

  • Simple and concise code using a built-in function
  • Can be used for arrays of any size, even at runtime
  • Automatically initializes the vector to the size of the array being assigned

Cons:

  • May be slower than other approaches for large arrays
  • Cannot preserve the order of elements if the range of iterators is not specified correctly
  • The assign function may not be supported by some older compilers or versions of the C++ language.

Code:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int arr[] = { 26,27,28,29,30}; // Example array
    int n = sizeof(arr) / sizeof(arr[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<int> vec;

    vec.assign(arr, arr + n); // Using the assign function

    // Printing the vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }

    return 0;
}

Output:

26 27 28 29 30 

Code Explanation:

  1. The code creates an integer array named “arr” and initializes it with values { 26 27 28 29 30 }.
  2. The number of elements in the array is calculated using the “sizeof” operator and stored in an integer variable “n”.
  3. A vector of integers named “vec” is declared.
  4.  Finally, a for loop is used to print the elements of the vector.

Approach 4: Using the vector resize function

The vector class with its incredible resize function, allows for the creation of a vector of a precise size. One can loop through the array, assigning each element to its corresponding index of the vector.

Pros:

  • Allows you to create a vector of a specific size
  • No need to use explicit iterators
  • Can be used for arrays of any size, even at runtime

Cons:

  • Requires explicit looping through the array and vector
  • May be slower than other approaches for large arrays
  • Cannot preserve the order of elements if the resize function is used incorrectly

Code:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int arr[] = { 35,36,37,38,39}; // Example array
    int n = sizeof(arr) / sizeof(arr[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<int> vec(n); // Using the resize function

    for (int i = 0; i < n; i++) {
        vec[i] = arr[i]; // Assigning elements from the array to the vector
    }

    // Printing the vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    cout << endl;

    return 0;
}

Output:

35 36 37 38 39

Code Explanation:

  1. An array of integers is defined with 5 elements.
  2. The number of elements in the array is calculated using the sizeof operator and is stored in the variable “n”.
  3. A vector of integers is created with the same size as the array, using the resize function.
  4. Finally, another loop is used to print out the elements of the vector.

Approach 5: Using the copy function

The algorithmic library can assist you in replicating elements from an array to a vector through the copy function. It takes in two iterators as arguments and allows you to pass in the beginning and end iterators of the array, which will generate a vector that contains the same elements.

.Pros:

  • Simple and efficient approach
  • No need to loop through the array or vector explicitly
  • Allows you to modify the vector as you copy elements

Cons:

  • Requires knowledge of iterators and their usage
  • Cannot be used if the array size is unknown at compile time
  • If the copy function is used incorrectly, it may lead to undefined behavior

Code:

#include <iostream>
#include <vector>
#include <algorithm> // For the copy function

using namespace std;

int main() {
    int arr[] = { 17,18,19,20,21}; // Example array
    int n = sizeof(arr) / sizeof(arr[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<int> vec(n); // Creating a vector of the same size as the array

    copy(arr, arr + n, vec.begin()); // Using the copy function

    // Printing the vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    
    return 0;
}

Output:

17 18 19 20 21 

Code Explanation:

  1. An array of integers is initialized and its size is determined using the sizeof operator.
  2. A vector of integers is created with the same size as the array.
  3. The copy function from the algorithm library is used to copy the contents of the array into the vector.
  4. The resulting vector is printed to the console using a for loop.

Approach 6: Using the initializer list constructor

The constructor that utilizes an initializer list for the vector class is a remarkable mechanism for the construction of a vector, as it furnishes the capability of fabricating a vector with an enlisting of elements. By making use of the well-placed curly braces to initialize the vector with the elements of the array.

Pros:

  • Simple and concise approach
  • Easy to understand and implement
  • Allows you to create a vector with a specific set of elements

Cons:

  • Cannot be used if the array size is unknown at compile time
  • Requires explicit listing out all the elements of the array
  • Cannot be used if the array is modified at runtime

Code:

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

int main() {
    int arr[] = {43,44,45,46,47,}; // Example array
    int n = sizeof(arr) / sizeof(arr[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<int> vec = { arr[0], arr[1], arr[2], arr[3], arr[4] }; // Using the initializer list constructor

    // Printing the vector
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    
    return 0;
}

Output:

43 44 45 46 47

 Code explanation:

  1. Declare an array of integers named “array” and initialize it with some values.
  2. Create a vector named “vec” and initialize it with the values of the array using the initializer list constructor.
  3. Print the elements of the vector using a for loop and the size() function of the vector.

Best Approach To Convert Array To Vector In C++

Here are the best qualities of the “Using the vector constructor” approach:

  1. Preserves the order of elements in the array: The vector constructor copies the elements of the array in the same order into the vector, preserving the original order of elements.
  1. Type-safe and compiler-checked: The use of iterators ensures type-safety and compile-time checking, preventing common errors such as accessing an array out of bounds or using the wrong data type.
  1. Simple and efficient: The code is concise and efficient, with no explicit looping through the array or vector required.

Sample Problems To Convert Array To Vector In C++

Sample Problem 1:

Scenario: An engineer needs to create a program to keep track of the parts used in a project. The parts are stored in an array, but the engineer wants to use a vector for easier manipulation.

Problem: The engineer has an array of 10 integers representing the part numbers used in the project. They want to convert this array into a vector using the vector constructor.

Solution Steps:

  1. An integer array named parts is initialized with ten integer values.
  2. A new vector of integers called partNumbers is created by passing the parts array to the vector constructor along with the n value, which is the size of the array.
  3. The contents of the partNumbers vector are printed using a for loop, and the program returns 0 to signify successful execution.

Code:

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

int main() {
    int parts[] = { 123, 456, 789, 234, 567, 890, 345, 678, 901, 123 }; // Example array
    int n = sizeof(parts) / sizeof(parts[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<int> partNumbers(parts, parts + n); // Using the vector constructor

    // Printing the vector
    for (int i = 0; i < partNumbers.size(); i++) {
        cout << partNumbers[i] << " ";
    }
    cout << endl;

    return 0;
}

Output:

123 456 789 234 567 890 345 678 901 123

Sample Problem 2:

Scenario: A mobile application developer needs to merge two arrays of data in their app. The data is stored in arrays, but the developer wants to combine them into a vector for easier manipulation.

Problem: The developer has two arrays of 5 integers each representing the user data and the app data. They want to combine these arrays into a single vector using the insert function.

Solution Steps:

  1. Prompt the user to enter a binary representation of boxes.
  2. Using a for loop, iterate over each character in the input string and determine whether it represents a box with chocolates or not using an if-else statement.
  3. If the character is ‘1’, add one to the total number of chocolates using bitwise operators, shifting the existing total left one bit and adding one. If the character is ‘0’, shift the total left one bit without adding one.
  4. Print the total number of chocolates in number format.

Code:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int userData[] = { 10, 20, 30, 40, 50 }; // Example array
    int appData[] = { 60, 70, 80, 90, 100 }; // Example array
    int n1 = sizeof(userData) / sizeof(userData[0]); // Number of elements in the first array
    int n2 = sizeof(appData) / sizeof(appData[0]); // Number of elements in the second array

    // Creating a vector from the arrays
    vector<int> data; // Empty vector
    data.insert(data.end(), userData, userData + n1); // Using the insert function to add the first array
    data.insert(data.end(), appData, appData + n2); // Using the insert function to add the second array

    // Printing the vector
    for (int i = 0; i < data.size(); i++) {
        cout << data[i] << " ";
    }
    cout << endl;

    return 0;
}

Output:

10 20 30 40 50 60 70 80 90 100

Sample Problem 3:

Scenario: A bike rental company needs to keep track of the bikes they have available for rent. The information about the bikes is stored in an array, but the company wants to use a vector to easily add or remove bikes as needed.

Problem: The bike rental company has an array of 6 strings representing the types of bikes they have for rent. They want to convert this array into a vector using the vector assign function.

Solution Steps:

  1. The program defines an array of string values named bikeTypes containing different types of bikes.
  2. It calculates the number of elements in the array by dividing the total size.
  3. It initializes an empty vector availableBikes and assigns all the elements of bikeTypes array to the vector using the assign function.
  4. Finally, it iterates through the vector using a for loop and prints each element of the vector on a new line using cout.

Code:

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

int main() {
    string bikeTypes[] = { "Mountain bike", "Road bike", "Electric bike", "BMX bike", "Hybrid bike", "Folding bike" }; // Example array
    int n = sizeof(bikeTypes) / sizeof(bikeTypes[0]); // Number of elements in the array

    // Creating a vector from the array using the vector assign function
    vector<string> availableBikes;
    availableBikes.assign(bikeTypes, bikeTypes + n); // Assigning the elements from the array to the vector

    // Printing the vector
    for (int i = 0; i < availableBikes.size(); i++) {
        cout << availableBikes[i] << endl;
    }

    return 0;
}

Output:

Mountain bike
Road bike
Electric bike
BMX bike
Hybrid bike
Folding bike

Sample Problem 4:

Scenario: A student needs to create a program to keep track of their textbooks for the semester. The information about the textbooks is stored in an array, but the student wants to use a vector to easily add and remove books as needed.

Problem: The student has an array of 4 strings representing the titles of their textbooks. They want to convert this array into a vector using the vector resize function.

Solution Steps:

  1. An array of string textbooks is defined with four elements: “Calculus”, “Chemistry”, “Psychology”, and “English”.
  2. The number of elements in the textbooks array is determined by dividing the total size of the array.
  3. An empty vector bookTitles is created, with its size initialized to the number of elements in the textbooks array. The elements of the textbooks array are then copied into the bookTitles vector using the copy function.
  4. Finally, the elements of the bookTitles vector are printed to the console using a for loop that iterates over the indices of the vector and outputs each element.

Code:

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

using namespace std;

int main() {
    string textbooks[] = { "Calculus", "Chemistry", "Psychology", "English" }; // Example array
    int n = sizeof(textbooks) / sizeof(textbooks[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<string> bookTitles; // Empty vector
    bookTitles.resize(n); // Resizing the vector to match the number of elements in the array
    copy(textbooks, textbooks + n, bookTitles.begin()); // Copying the elements from the array to the vector

    // Printing the vector
    for (int i = 0; i < bookTitles.size(); i++) {
        cout << bookTitles[i] << " ";
    }
    cout << endl;

    return 0;
}

Output:

Calculus Chemistry Psychology English

Sample Problem 5:

Scenario: A person is packing for a weekend trip and wants to keep track of the items they need to bring. They have a list of items stored in an array, but they want to use a vector to easily add or remove items.

Problem: The person has an array of 5 strings representing the items they need to pack. They want to convert this array into a vector using the copy function.

Solution Steps:

  1. Declares an array of string values named items which contains some example packing items.
  2. The number of elements in the “items” array is calculated using the sizeof operator and stored in the integer variable “n”.
  3. Creates a vector named packingList with n elements, and copies the elements from the items array to the vector using the copy() function.
  4. Prints out the elements of the packingList vector using a for loop, with each element separated by a space.

Code:

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

using namespace std;

int main() {
    string items[] = { "Toothbrush", "Toothpaste", "Clothes", "Phone charger", "Book" }; // Example array
    int n = sizeof(items) / sizeof(items[0]); // Number of elements in the array

    // Creating a vector from the array
    vector<string> packingList(n); // Vector with n elements
    copy(items, items + n, packingList.begin()); // Using the copy function to copy the elements from the array to the vector

    // Printing the vector
    for (int i = 0; i < packingList.size(); i++) {
        cout << packingList[i] << " ";
    }
    return 0;
}

Output:

Toothbrush Toothpaste Clothes Phone charger Book

Sample Problem 6:

Scenario: A doctor is keeping track of their patients and their medical conditions. The information is currently stored in an array, but the doctor wants to use a vector for easier manipulation.

Problem: The doctor has an array of 3 strings representing the patient names and their medical conditions. They want to convert this array into a vector using the initializer list constructor.

Solution Steps:

  1. The program prompts the user to enter a binary representation of a sales report.
  2. The program iterates through each character in the binary sales report string, and for each character, it performs a bitwise left shift operation on the totalSales variable (which is initialized as 0), followed by a bitwise OR operation with the result of subtracting ‘0’ from the binary character. This converts the binary string to an integer using bit manipulation.
  3. The program displays the total number of sales made by outputting the value stored in the totalSales variable after the binary conversion, in a simple number format.
  4. The program returns 0 to indicate successful completion and termination of the program.

Code:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    // Example array
    string patientData[] = {"John (diabetes)", "Sara (asthma)", "Mark (hypertension)"};

    // Creating a vector from the array using the initializer list constructor
    vector<string> patients = {patientData[0], patientData[1], patientData[2]};

    // Printing the vector
    for (int i = 0; i < patients.size(); i++) {
        cout << patients[i] << endl;
    }

    return 0;
}

Output:

John (diabetes)
Sara (asthma)
Mark (hypertension)

Conclusion:

In conclusion, converting an array to a vector in C++ can be done using several approaches. We explored six approaches, but Using the vector constructor came as the best approach.

Choosing the right approach depends on factors such as performance requirements, code complexity, and maintainability.