The Wayback Machine - https://web.archive.org/web/20240712214023/https://www.geeksforgeeks.org/initialize-a-vector-in-cpp-different-ways/
Open In App

7 ways to Initialize Vector in C++

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

Vectors in C++, like Arrays, are one of the most extensively used entities and to initialize vectors in C++ is one of the most common issues that users face. One of the most commonly used methods for vector initialization is the Array style. But C++, along with this, provides several different methods to initialize a vector. In this post, we have looked into such 7 different ways of how you can initialize Vectors in C++.

Let us look into them one by one:

1. Initializing Vector by Pushing values One by One

Vector can be initialized by pushing value one by one. This method involves creating an empty vector and adding elements to it one by one using the push_back() function.

Syntax

vector_name.push_back(value)

Example

C++
// C++ program to create an empty
// vector and push values one
// by one.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Create an empty vector
    vector<int> vect;

    vect.push_back(10);
    vect.push_back(20);
    vect.push_back(30);

    for (int x : vect)
        cout << x << " ";

    return 0;
}

Output
10 20 30 

Time Complexity: O(n), where n is the number of elements being pushed.
Auxiliary Space: O(n), where n is the number of elements being stored.

2. Initializing Vector by Specifying Size and Initializing All Values

In this method, we create a vector of a specified size and initialize all elements to the same value. We do it by passing the size and the default value to the vector constructor in vector declaration.

Syntax

vector<type> vector_name(size, default_value);

Example

C++
// C++ program to create an empty 
// vector and push values one
// by one.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int n = 3;

    // Create a vector of size n with
    // all values as 10.
    vector<int> vect(n, 10);

    for (int x : vect)
        cout << x << " ";

    return 0;
}

Output
10 10 10 

Time Complexity: O(n), where n is the size of the vector.
Auxiliary Space: O(n), where n is the size of the vector.

3. Initializing Vector like Arrays

We can initialize a vector with a list of values similar to how you would initialize an array. This can be by passing assigning the list of values to the vector during vector declaration.

Syntax

vector<type> vector_name = {v1, v2, v3 ....};

Example

C++
// C++ program to initialize 
// a vector like an array.
#include <iostream>
#include <vector>
using namespace std;

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

    for (int x : vect)
        cout << x << " ";

    return 0;
}

Output
10 20 30 

Time Complexity: O(n), where n is the number of elements being initialized.
Auxiliary Space: O(n), where n is the number of elements being stored.

4. Initializing Vector from an Array

A vector can be initialized using an existing array. We just need to pass the pointer to the first element of the array and the hypothetical element after the last element of the array.

Syntax

vector<type> vector_name(arr, arr + size);

Example

C++
// C++ program to initialize
// a vector from an array.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int arr[] = { 10, 20, 30 };
    int n = sizeof(arr) / sizeof(arr[0]);

    vector<int> vect(arr, arr + n);

    for (int x : vect)
        cout << x << " ";

    return 0;
}

Output
10 20 30 

Time Complexity: O(n), where n is the number of elements in the array.
Auxiliary Space: O(n), where n is the number of elements being stored.

5. Initializing Vector from Another Vector

Like previous method, we can create a new vector by copying elements from an existing vector using iterators. We pass the begin() and end() iterator of the another vector to the vector constructor.

Syntax

vector<type> vector_name(vec1.begin(), vec1.end());

Example

C++
// C++ program to initialize a vector from
// another vector.
#include <iostream>
#include <vector>
using namespace std;

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

    vector<int> vect2(vect1.begin(), vect1.end());

    for (int x : vect2)
        cout << x << " ";

    return 0;
}

Output
10 20 30 

Time Complexity: O(n), where n is the number of elements in the source vector.
Auxiliary Space: O(n), where n is the number of elements being stored

6. Initializing all Elements of Vector with a Particular Value

We can also use the std::fill function to initialize all elements of a vector to the same value. This method is similar to the method 2 but we need to pass the begin and end iterator of the vector to the fill method along with the value to be filled.

Syntax

fill(vector_name.begin(), vector_name.end(), value);

Example

C++
// C++ Program to initialize vector using fill()
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // creating array with size 10
    vector<int> vect1(10);

    // initializing using fill() function
    int value = 5;
    fill(vect1.begin(), vect1.end(), value);

    // printing vector
    for (int x : vect1)
        cout << x << " ";

    return 0;
}

Output
5 5 5 5 5 5 5 5 5 5 

Time Complexity: O(n), where n is the size of the vector.
Auxiliary Space: O(1) additional space for the value variable.

7. Initialize Vector with Consecutive Numbers using std::iota

The iota function from the <numeric> library allows you to initialize a vector with consecutive values efficiently. We need to pass the begin and end iterator with the value of the first element to the iota() function.

Syntax

iota(vector_name.begin(), vector_name.end(), value);

Example

C++
// C++ program to initialize a 
// vector with consecutive
// numbers
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

int main()
{
    // declaring a vector with size 5
    vector<int> vec(5);

    // initializing using iota()
    iota(vec.begin(), vec.end(), 1);

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

Output
1 2 3 4 5 

Time Complexity: O(n), where n is the size of the vector.
Auxiliary Space: O(1) additional space for the iota function.



Previous Article
Next Article

Similar Reads

How to Initialize 3D Vector in C++ STL?
Prerequisite: Vector in C++ Vectors in C++ are the same as arrays with dynamic sizes having the ability to resize themselves, we can insert and remove elements from the end. 3-D Vector A 3D vector is a type of vector having 3 Dimensions means a vector storing a 2-D vector inside it, similar to a 2-D array. There are a few methods to initialize a 3D
3 min read
Different Ways to Initialize an unordered_set in C++
An unordered_set is an associated container available in the C++ Standard Template Library(STL) that is used for unique elements without any specific ordering, it internally uses the working principle of a hashtable to store elements. Different ways to Initialize an unordered_set in C++ Initialization using the default constructorInitialization usi
6 min read
Different Ways to Initialize a Map in C++
Map is an associative container available in the C++ Standard Template Library(STL) that is used to store key-value pairs. Let's see the different ways to initialize a map in C++. Initialization using assignment and subscript operatorInitialization using an initializer listInitialization using an array of pairsInitialization from another map using
5 min read
Different Ways to Initialize an Set in C++
A set is an associative container available in the C++ Standard Template Library(STL) that is used for unique elements in a specific order, it internally uses the working principle of a Binary Search Tree to store elements. Different Ways to Initialize a set in C++: Initialization using the default constructor.Initialization using initializer list.
5 min read
Different Ways to Initialize an unordered_map in C++
unordered_map is an associated container available in the C++ Standard Template Library(STL) that is used to store key-value pairs. It internally uses the working principle of a hashmap to store key-value pairs. Different ways to initialize an unordered_map in C++: Initialization using assignment and subscript operatorInitialization using an initia
5 min read
Different Ways to Initialize a List in C++ STL
Prerequisite: List in C++ Lists are sequence containers that allow non-contiguous memory allocation The following are the different ways to create and initialize a List in C++ STL. Initializing an empty List and pushing values one by oneSpecifying List size and initializing all valuesInitializing List like the arraysInitializing a list from an arra
6 min read
vector::front() and vector::back() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::front() This function can be used to fetch the first element of a vector container.Syntax : vectorname.front() Parameters : No value is needed to pass as
3 min read
vector::empty() and vector::size() in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::empty() The empty() function is used to check if the vector container is empty or not.Syntax : vectorname.empty() Parameters : No parameters are p
5 min read
vector::push_back() and vector::pop_back() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::push_back() push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the cur
4 min read
vector::at() and vector::swap() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::at() at() function is used reference the element present at the position given as the parameter to the function. Syntax: vectorname.at(position) Parameter
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg