How to initialize a vector in C++

In this blog post, you will learn how to initialize a vector in C++ with the help of C++ programs. I have already written an article on vectors if you want you can check it; “C++ vectors“.

Now comes the topic of how we can initialize the C++ vector. I will go through the different ways of initializing a vector in C++. I will divide them into sub-sections and explain them with C++ programs.

So let’s get started,

 

1. How to Initialize a Vector When Declaring the Vector in C++:

Similar to the fixed-size arrays, you can initialize a vector with value when it is being declared. Consider the below example, in which declaration and initialization happen at the same time.

Example 1:

/*
How to Initialize a Vector When
Declaring the Vector in C++

*/

#include <iostream>
#include <vector>

int main()
{
    //initialization at the time of declaration
    std::vector<int> vec{ 27, 6, 8, 24, 23 };

    for (int x : vec)
    {
        std::cout << x << " ";
    }

    return 0;
}

Output:

27 6 8 24 23

In the above example, both the declaration and initialization of the vector were done at the same time. At the time of declaration, I am assigning five integer numbers and printing the same with the help of a for loop.

 

Example 2:

/*
How to Initialize a Vector When
Declaring the Vector in C++

*/

#include <iostream>
#include <vector>

int main()
{
    //initialization at the time of declaration
    std::vector<std::string> vec{ "aticleworld", "amlendra","pooja"};

    for (std::string x : vec)
    {
        std::cout << x << "  ";
    }

    return 0;
}

Output:

aticleworld amlendra pooja

In the above example, I am creating a vector of strings and initializing it with the three strings.

 

2. How to Initialize a Vector From an Array in C++:

You can initialize a vector from an existing array. In the below example, I will show you how you can initialize the vector with an existing array.

You need to create and initialize an array first; then copy all the elements of the array into the created vector using two vector methods – begin() and end(). See the below example for a better understanding.

/*
How to Initialize a Vector From an Array in C++:
*/

#include <iostream>
#include <vector>

int main()
{
    int arr[] = { 27, 6, 8, 24, 23 };

    std::vector<int> vec(std::begin(arr), std::end(arr));
    for (int x : vec)
    {
        std::cout << x << " ";
    }

    return 0;
}

Output:

27 6 8 24 23

 

I believe, now you are thinking about how the above code works and initialize the vector with an array.

Don’t worry I will solve your query.

The vector class supports multiple constructors; for the above declaration it uses the below constructor;

//one of the vector class constructor

template<class InputIterator>
constexpr vector(InputIterator first, InputIterator last,
const Allocator& = Allocator());

It constructs a vector equal to the range [first, last), using the specified allocator. Now I believe able to understand but still, if you have any questions, you can write your question in the comment box.

Note:Here, I have used begin() and end() where begin() is used to return an iterator that is pointing to the first element of the vector, and end() is used to return an iterator that is next to the last element of the vector. Besides the begin() and end() if you want; you can pass the (arr, (arr+size)); it works in the same way.

/*
How to Initialize a Vector From an Array in C++:
*/

#include <iostream>
#include <vector>

int main()
{
    int arr[] = { 27, 6, 8, 24, 23 };

    // Determining the size of the array.
    int size = sizeof(arr) / sizeof(arr[0]);

    std::vector<int> vec(arr, (arr+size));
    for (int x : vec)
    {
        std::cout << x << " ";
    }

    return 0;
}

Output:

27 6 8 24 23

 

3. How to initialize a Vector From another initialized Vector:

You initialize a vector from another vector using the same concept that I used for an array in the above example. Consider the below example code.

/*
How to initialize a Vector From
another initialized Vector:
*/

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vect1{ 10, 20, 30 };
    std::vector<int> vect2(vect1.begin(), vect1.end());

    for (int x : vect2)
    {
        std::cout << x << " ";
    }

    return 0;
}

Output:

10 20 30

 

4. How to initialize a C++ vector Using the push_back():

The push_back() method allows us to push new items to the last index of a vector. Consider the below example code.

/*
How to initialize a C++ vector
Using the push_back():
*/

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec;
    vec.push_back(27);
    vec.push_back(6);
    vec.push_back(8);
    vec.push_back(24);
    vec.push_back(23);

    for (int x : vec)
    {
        std::cout << x << " ";
    }

    return 0;
}

Output:

27 6 8 24 23

 

 

5. How to Initialize a Vector by Specifying the Size and Value in C++:

You can specify the size and items of a vector during its declaration. We use this mainly in situations where the vector is required to have a specific value all through. Consider the below code for a better understanding,

/*
How to Initialize a Vector by
Specifying the Size and Value in C++:
*/

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec(5, 27);

    for (int x : vec)
    {
        std::cout << x << " ";
    }

    return 0;
}

Output:

27 27 27 27 27

This type of initialization is supported by the above code because the vector class has the below constructor,

//Constructor of the vector class

constexpr vector(size_type n, const T& value,
const Allocator& = Allocator());

This constructor helps to construct a vector with n copies of value, using the specified allocator.  That means the first parameter is the maximum number of vector elements and the second parameter is the value that is stored in the vector.

 

6. How to initialize an array with consecutive numbers using std::iota :

Before writing the code I want to give a short summary about the iota() method which help you to understand the code. Let’s first see the syntax,

//Defined in header <numeric>

template< class ForwardIt, class T >
void iota( ForwardIt first, ForwardIt last, T value ); (since C++11) (until C++20)


template< class ForwardIt, class T >
constexpr void iota( ForwardIt first, ForwardIt last, T value ); (since C++20)

The iota() method takes three parameters, first, last, and value, where first and last denote the iteration from initial to final positions in a sequence, and value denotes the initial value from which the sequence starts.

The iota() method fills the range [first, last) with sequentially increasing values, starting with value and repetitively evaluating ++value.

/*
How to initialize an array with
consecutive numbers using std::iota :
*/

#include <iostream>
#include <vector>
#include <numeric>

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

    // initializing using iota()
    iota(vec.begin(), vec.end(), 10);
    for (int x : vec)
    {
        std::cout << x << " ";
    }

    return 0;
}

Output:

10 11 12 13 14

In the above program, I created a vector of size 5 and after that, for initialization, I used the iota() method.  The iota method stores the increasing value of numbers starting from 10 to 14.

 

7. How to initialize a vector with consecutive numbers using std::fill:

Using the fill() method you can also initialize the the vector. The fill() method assigns the given value to the elements in the range [first, last).

//Defined in header <algorithm>

template< class ForwardIt, class T >
void fill( ForwardIt first, ForwardIt last, const T& value ); (until C++20)


template< class ForwardIt, class T >
constexpr void fill( ForwardIt first, ForwardIt last, const T& value ); (since C++20)

 

Consider the below code for the understanding in which I have used the fill() method to assign the value to the vector.

/*
How to initialize an array with
consecutive numbers using std::fill:
*/

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

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

    // initializing using iota()
    fill(vec.begin(), vec.end(), 20);
    for (int x : vec)
    {
        std::cout << x << " ";
    }

    return 0;
}

Output:

20 20 20 20 20

 

Recommended Articles for you:

Leave a Reply

Your email address will not be published. Required fields are marked *