How to Initialize a Vector in C++?
Overview
In C++, the vector is an STL container that shows the dynamic representation of an array whose size can be maximized or minimized depending on the program's requirement. They are used to store elements of similar data types in a contiguous way, like an array, but unlike an array, the size of a vector can grow or shrink dynamically.
A vector can be declared and initialized in different ways, including pushing every value one by one, specifying the size of the vector, and then initializing all values, etc.
Introduction
Vectors are the dynamic representations of an array. Vector is part of the C++ Standard Template Library. They are used to store the elements dynamically. Vectors are STL containers with a special feature to increase or decrease the size considering the requirement of insertion and deletion inside a program.
The process of inserting and deleting elements starts from the last to the first. Deletion takes constant time, while insertion takes differential time as a vector needs to resize after accumulating the elements.
To use Vector inside a C++ program, we have to include the <vector> header file.
In the case of a static array, we cannot insert elements once it is full. Still, when a vector's size becomes full, it doubles(or similar exponential growth depending on the compiler) its size from the original. That's why using a vector instead of a static array is beneficial.
The vector class contains different member functions, just like other STL containers. Those member functions are as follows:- a) Iterators b) Capacity c) Modifiers
-
Iterators: Iterators are used to traverse and locate vectors. That is why contiguous memory is allocated to a vector to store the elements. There are different types of iterators in vector containers which are as follows:
- cbegin(), cend(), begin(), end(), rbegin(), rend(), crbegin(), crend().
- In this article, we will use iterators like 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 which is next to the last element of the vector.
-
Capacity: The member function constituting a vector's size and capacity in C++. There are different types of capacity in a vector which are as follows:
- size(), max_size(), reserve(), shrink_to_fit(), capacity(), empty(), resize(n).
- In this article, we will use capacity functions like size() and capacity() where size() is used to return the size of a vector and capacity() is used to return the maximum storage capacity allocated to a vector.
- Modifiers: The functions used to modify a vector by adding or removing elements. There are different types of modifiers in a vector which are as follows:
- push_back(), pop_back(), insert(), assign(), erase(), swap(), clear().
- In this article, we will use the modifier push_back(), which is used to push elements or insert elements inside a vector.
Now, let's discuss the initialization of a vector inside a C++ program.
Vector need not be initialized with size like a normal array. They use the reference of an object, which means they do not directly contain the data. Instead, they point to the object that contains the respective data. Vectors can adjust depending upon the number of references of the object or number of elements which can be done because the container automatically controls their storage. The container in STL contains a copy to allocate the memory for a lifetime. Iterators are used to traverse and locate vectors, so contiguous memory is allocated to store the elements inside a vector.
Unlike arrays, vector utilizes more memory to manage the storage and grow dynamically. Accessing the elements inside a vector takes a bit more time than in an array.
Now, let's learn about different ways to initialize vector C++ with the help of examples to understand it more clearly.
How to Initialize a Vector in C++? What are the Different Ways to Initialize a Vector in C++?
There exist several ways to create and initialize a vector in C++. Let's discuss them in detail:
Initialize by Pushing Values One by One
In this method, we will push the elements one after the other inside the vector using the push_back() function. The push_back() method inserts the new element at the end of a vector, and every time the size of the vector is increased by one (1).
Code
Output
Explanation
In the above program, we have declared an empty vector nums of integer type. Then we inserted elements in the vector using the push_back() modifier.
After inserting the elements, we printed every element inserted in the vector using the for loop, as seen in the output.
Specifying Size and Initializing all Values
In this method, we will specify the size of the vector at the time of declaration and initialize all elements of the vector using the for a loop.
Code
Output
Explanation
In the above program, we have declared a vector of integer type nums with the specified size equal to 5. After specifying the size of the vector, we have initialized the values using the for loop starting from 1 up to 5.
Then we used another way of declaring the vector, which also works like the above method. In this method, we have declared the vector nums1 of integer type with a size equal to 6 and a value equal to 8.
After initializing the values, we printed the vector elements using the for loop.
Initializing like Arrays
In this method, we will initialize a vector like an array using curly braces with values. The elements will be inserted inside the vector in the same order, and its size will be adjusted depending on the number of elements.
Code
Output
Explanation In the above program, we have initialized a vector with the value nums. It is done in the same way used for initializing the values of an array.
After initializing the values, we will print the values inside the vector using for loop.
Initializing from an Array
In this method, we will initialize a vector using an existing array. Here we will initialize an array and then pass the elements of the array to the vector. It is one of the most usual ways to initialize a vector in C++.
Note: Here, we have passed the starting index as well as the last index of the array using (array, array + size), which works in the same way as vector.begin() and vector.end() does. These iterators are used and explained in the next section. Please refer to it.
Code
Output:
Explanation
In the above program, we have initialized an array array[], which is of integer type. We initialized the array and then calculated its size stored in the size variable. We have created a vector nums of integer type, which is initialized from the array we created earlier. Then we printed the elements inside the vector using a for a loop.
Using Another Vector for Initialization
This method will initialize a new vector using an existing one. We will pass the iterator (begin(), end()) pointing to the existing vector to create a new vector. vector.begin() is used to return an iterator pointing to the first element of the vector, and vector.end() is used to return an iterator next to the vector's last element.
The elements inside the existing vector will be passed as an argument and inserted inside the new vector.
Code
Output
Explanation
In the above program, we have initialized two vectors, nums2 and nums3. We have used an already initialized vector nums1 with its values to initialize the values of the other two vectors by passing the iterators nums.begin() and nums.end().
We have initialized vector nums2 with all values of nums1 and nums3 up to 2 elements of nums1 as seen in the program.
After initialization, we traversed every element of num2 and num3 and then printed them using for loops.
Using a Particular Value to Initialize all Vectors
In this method, we will use a particular value to initialize all the elements in a vector. fill() method is used to fill or assign all the elements a specified value within a specified range. It accepts three arguments: ' begin(), end()`, and value.
Code
Output
Explanation
In the above program, we have initialized a vector nums with its size equal to 5. Then we provided the input, which specifies the value to be initialized to all vector elements.
Then we used the fill() method to initialize the vector with a particular value. fill() function takes three parameters nums.begin(), nums.end(), and value. After initializing the vector, we traversed it and printed its elements(using the for loop).
Using std::iota to Initialize an Array with Consecutive Numbers
In this method, we will initialize using std::iota(). The iota() method generates a sequence of consecutive numbers. It 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.
Code
Output
Explanation
In the above program, we have initialized an array nums of integer type with a size equal to 10. After initialization, we used the iota() method to store the increasing value of numbers starting from 1 to 4 as seen in the program.
After initialization of values in the array, we will traverse the array, and after traversing, we will print the array elements using a for loop.
Learn More
In this article, we have discussed the initialization of vectors in C++. To learn more about Vectors in C++, please refer to Vector in C++.
Conclusion
- Vector is the part of C++ Standard Template Library (STL). They are used to store the elements dynamically.
- To use vector inside a C++ program, we must include a <vector> header file.
- Vector need not be initialized with size like a normal array. They use the reference of an object, which means they do not directly contain the data. Instead, they point to the object that contains the respective data.
- Unlike arrays, vector utilizes more memory to manage the storage and grow dynamically. Accessing the elements inside a vector takes a bit more time than in an array.
- Initialize vector C++ can be done in different ways, including pushing each value one by one, specifying the size of the vector and then initializing all values, using std::iota to initialize elements with consecutive values, etc.