How to Initialize a Vector in C++ in 6 Different Ways [Updated] (2024)

Ways to Initialize a Vector in C++

The following different ways can be used to initialize vector in C++:

  • Using the push_back() Method to Push Values Into the Vector

The push_back() method of the class vector is used to push or insert elements into a vector. It inserts each new element at the end of the vector and the vector size is increased by 1.

Syntax

vector_name.push_back(data)

vector_name is the name of the vector. The push_back() method accepts one element and inserts it at the end of the vector.

Example

Consider a vector v1.

Input: v1.push_back(100)

v1.push_back(200)

v1.push_back(300)

Output: Resulting vector is:

100 200 300 with size 3.

Input: v1.push_back(1)

v1.push_back(2)

Output: Resulting vector is:

100 200 300 1 2 with size 5.

The following program illustrates how to initialize a vector in C++ using the push_back() method:

#include <iostream>

#include <vector>

using namespace std;

int main() {

// declare a vector

vector<int> v1;

// initialize vector using push_back()

v1.push_back(100);

v1.push_back(200);

v1.push_back(300);

v1.push_back(1);

v1.push_back(2);

cout << "The elements in the vector are:\n";

// traverse vector

for (int i = 0; i < v1.size(); i++)

{

// print the vector elements

cout << v1[i] << " ";

}

return 0;

}

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (1)

Full Stack Web Developer Course

To become an expert in MEAN StackView Course

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (2)

Steps

  1. Declare a vector v1.
  2. Initialize the vector using the push_back() method. Insert vector elements one by one
  3. Traverse the vector
  4. Print the vector elements
  • Using the Overloaded Constructor

The overloaded constructor can also be used to initialize vectors in C++. This constructor accepts two parameters. The size of the vector and the value to be inserted is provided while initializing the vector. The value provided will be inserted into the vector multiple times (equal to the provided size of the vector).

Syntax

vector<type> vector_name(size, data)

The parameter size is the number of elements to be inserted into the vector (or simply the size of the vector) and the data is the value to be inserted.

Also Read: Constructor in C++: A Comprehensive Guide to Constructor

Example

Input: vector<int> v1(5, 2)

Output: The resulting vector will be:

2 2 2 2 2

Input: vector<int> v2(4, 1)

Output: The resulting vector will be:

1 1 1 1

The following program illustrates how to initialize a vector in C++ using the overloaded constructor:

#include <iostream>

#include <vector>

using namespace std;

int main()

{

// initialize size

int size = 5;

// initialize vector using overloaded constructor

vector<int> v1(size, 2);

// print the vector elements

cout << "The vector v1 is: \n";

for (int i = 0; i < v1.size(); i++)

{

cout << v1[i] << " ";

}

cout << "\n";

// initialize vector v2

vector<int> v2(4, 1);

// print elements of vector v2

cout << "\nThe vector v2 is: \n";

for (int i = 0; i < v2.size(); i++)

{

cout << v2[i] << " ";

}

cout << "\n\n";

return 0;

}

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (3)

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (4)

Steps

  1. Initialize the size of the vector
  2. Initialize the vector using the overloaded constructor by specifying the size and the value to be inserted
  3. Traverse the vector
  4. Print the vector elements
  • Passing an Array to the Vector Constructor

Another way to initialize a vector in C++ is to pass an array of elements to the vector class constructor. The array elements will be inserted into the vector in the same order, and the size of the vector will be adjusted automatically.

Syntax

vector<type> vector_name{array of elements}

You pass the array of elements to the vector at the time of initialization.

Example

Input: vector<int> v1{10, 20, 30, 40, 50}

Output: The resulting vector will be:

10 20 30 40 50

Input: vector<char> v2{'a', 'b', 'c', 'd', 'e'}

Output: The resulting vector will be:

a b c d e

The following program illustrates how to initialize a vector in C++ by passing an array to the vector class constructor:

#include <iostream>

#include <vector>

using namespace std;

int main()

{

// pass an array of integers to initialize the vector

vector<int> v1{10, 20, 30, 40, 50};

// print vector elements

cout << "The vector elements are: \n";

for (int i = 0; i < v1.size(); i++)

{

cout << v1[i] << " ";

}

cout << "\n\n";

// pass an array of characters to initialize the vector

vector<char> v2{'a', 'b', 'c', 'd', 'e'};

// print vector elements

cout << "The vector elements are: \n";

for (int i = 0; i < v2.size(); i++)

{

cout << v2[i] << " ";

}

cout << "\n\n";

return 0;

}

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (5)

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (6)

Steps

  1. Declare a vector
  2. Initialize the vector. Pass an array of elements to the vector class constructor
  3. Traverse the vector
  4. Print the vector elements
  • Using an Existing Array

This is one of the most standard ways to initialize vectors in C++ elegantly. You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class.

Also Read: Iterators in C++: An Ultimate Guide to Iterators

Syntax

data_type array_name[n] = {1,2,3};

vector<data_type> vector_name(arr, arr + n)

The array of size n is passed to the iterator constructor of the vector class.

Example

Input: int a1[5] = {10, 20, 30, 40, 50}

vector<int> v1(a1, a1 + 5)

Output: The resulting vector will be:

10 20 30 40 50

Input: char a2[5] = {'a', 'b', 'c', 'd', 'e'}

vector<int> v2(a2, a2 + 5)

Output: The resulting vector will be:

a b c d e

The following program illustrates how to pass an existing array to the iterator constructor of the vector class to initialize a vector in C++:

#include <iostream>

#include <vector>

using namespace std;

int main()

{

// initialize an array of integers

int a1[5] = {10, 20, 30, 40, 50};

// initialize vector

vector<int> v1(a1, a1 + 5);

// print vector elements

cout << "The vector elements are: \n";

for (int i = 0; i < v1.size(); i++)

{

cout << v1[i] << " ";

}

cout << "\n\n";

// initialize an array of char

char a2[5] = {'a', 'b', 'c', 'd', 'e'};

vector<int> v2(a2, a2 + 5);

// print vector elements

cout << "The vector elements are: \n";

for (int i = 0; i < v2.size(); i++)

{

cout << v2[i] << " ";

}

cout << "\n\n";

return 0;

}

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (7)

Caltech Coding Bootcamp

Become a full stack developer in 6 monthsEnroll Now

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (8)

Steps

  1. Initialize an array
  2. Pass the array to the iterator constructor of the vector class to initialize the vector
  3. Traverse the vector
  4. Print the vector elements
  • Using an Existing Vector

The range constructor of the vector class can also be used to initialize a vector. You pass the iterators of an existing vector to the constructor to specify the range of the elements to be inserted into the new vector.

Syntax

vector<type> vector_name(iterator_first, iterator_last)

Here, you must pass the iterators pointing to the existing vector to the constructor, to initialize the new vector. The elements lying in the range that is passed as arguments are inserted into the new vector.

Example

Input: vector<int> v1{10, 20, 30, 40, 50};

vector<int> v2(v1.begin(), v1.end())

Output: The resulting vector will be:

10 20 30 40 50

Input: vector<int> v1{10, 20, 30, 40, 50};

vector<int> v2(v1.begin(), v1.begin() + 3)

Output: The resulting vector will be:

10 20 30

The following program illustrates how to initialize a vector in C++ using an existing vector:

#include <iostream>

#include <vector>

using namespace std;

int main()

{

// initialize a vector

vector<int> v1{10, 20, 30, 40, 50};

// initialize vectors using the range constructor

vector<int> v2(v1.begin(), v1.end());

vector<int> v3(v1.begin(), v1.begin() + 3);

// print vector elements

cout << "The vector elements are: \n";

for (int i = 0; i < v2.size(); i++)

{

cout << v2[i] << " ";

}

cout << "\n\n";

// print vector elements

cout << "The vector elements are: \n";

for (int i = 0; i < v3.size(); i++)

{

cout << v3[i] << " ";

}

cout << "\n\n";

return 0;

}

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (9)

Steps

  1. Initialize a vector using any of the methods discussed above
  2. Pass the iterators of this vector (specifying the range) to the range constructor of the new vector
  3. Traverse the vector
  4. Print the vector elements
  • Using the fill() Method

The fill() function, as the name suggests, fills or assigns all the elements in the specified range to the specified value. This method can also be used to initialize vectors in C++.

Syntax

fill(begin, end, value)

The fill() function accepts three parameters begin and end iterators of the range and the value to be filled. The iterator begin is included in the range whereas the iterator end is not included.

Example

Consider vectors v1 and v2 of size 5.

Input: fill(v1.begin(), v1.end(), 6)

Output: The resulting vector will be:

6 6 6 6 6

Input: fill(v2.begin() + 2, v2.begin() + 4, 6)

Output: The resulting vector will be:

0 0 6 6 0

The following program illustrates how to initialize a vector in C++ using the fill() function:

#include <iostream>

#include <vector>

using namespace std;

int main()

{

// declare a vector

vector<int> v1(5);

// initialize the vector using the fill() method

fill(v1.begin(), v1.end(), 6);

// declare another vector

vector<int> v2(5);

// initialize v2

fill(v2.begin() + 2, v2.begin() + 4, 6);

// print vector elements

cout << "The vector elements are: \n";

for (int i = 0; i < v1.size(); i++)

{

cout << v1[i] << " ";

}

cout << "\n\n";

// print vector elements

cout << "The vector elements are: \n";

for (int i = 0; i < v2.size(); i++)

{

cout << v2[i] << " ";

}

cout << "\n\n";

return 0;

}

How to Initialize a Vector in C++ in 6 Different Ways [Updated] (10)

Steps

  1. Declare a vector
  2. Pass the range and the value to the fill() function to initialize the vector
  3. Traverse the vector
  4. Print the vector elements
Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!
How to Initialize a Vector in C++ in 6 Different Ways [Updated] (2024)

FAQs

How do you initialize a vector in C ++? ›

You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.

What is the correct way to initialize vector in C ++? Mcq? ›

Algorithm
  1. Begin.
  2. Declare v of vector type.
  3. Then we call push_back() function. This is done to insert values into vector v.
  4. Then we print "Vector elements: \n".
  5. " for (int a: v)
  6. print all the elements of variable a."

How do you update a vector in C++? ›

vector :: assign() in C++ STL

vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.

How do you initialize a vector with the same value in C++? ›

How to initialize a vector in C++
  1. Pushing the values one-by-one. All the elements that need to populate a vector can be pushed, one-by-one, into the vector using the vector class method​ push_back . ...
  2. Using the overloaded constructor of the vector class. ...
  3. Using arrays. ...
  4. Using another, already initialized, vector.

Are vectors initialized to zero C++? ›

A vector, once declared, has all its values initialized to zero.

How do you initialize all elements of an array to 0 in C++? ›

The entire array can be initialized to zero very simply. This is shown below. int arr[10] = {0};

What is the default value of vector in C++? ›

The default value of a vector is 0.

What are the vectors in C++ Mcq? ›

Explanation: Vectors are just like arrays with the ability to resize itself whenever an element is added to or deleted from it.

How do you initialize a map in C++? ›

Let's see the different ways to initialize a map in C++.
  1. Initialization using assignment and subscript operator.
  2. Initialization using an initializer list.
  3. Initialization using an array of pairs.
  4. Initialization from another map using the map.insert() method.
  5. Initialization from another map using the copy constructor.
13 Apr 2022

How do you update data in vector? ›

We can directly enter the new or updated value using the '=' operator to assign the value to that location. For instance, the vector element at index 4 is modified as -1 in this case.

What is vector in C++ with example? ›

Vectors in C++ are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.

How do you modify a vector? ›

How can I edit vector files? Vector images are often saved as AI files to enable quick editing. These files are editable in Adobe Illustrator. Images saved in this format can also be converted to PDF files, allowing them to be edited in Adobe Acrobat and making them easier to print.

How do you initialize a variable in C++? ›

Variable initialization in C++

There are two ways to initialize the variable. One is static initialization in which the variable is assigned a value in the program and another is dynamic initialization in which the variables is assigned a value at the run time.

How do you initialize a vector with a specific size? ›

To initialize a two-dimensional vector to be of a certain size, you can first initialize a one-dimensional vector and then use this to initialize the two-dimensional one: vector<int> v(5); vector<vector<int> > v2(8,v); or you can do it in one line: vector<vector<int> > v2(8, vector<int>(5));

How do you initialize a string in C++? ›

Creating and initializing C++ strings
  1. Create an empty string and defer initializing it with character data.
  2. Initialize a string by passing a literal, quoted character array as an argument to the constructor.
  3. Initialize a string using the equal sign (=).
  4. Use one string to initialize another.

Can I compare two vectors C++? ›

The C++ function std::vector::operator== tests whether two vectors are equal or not. Operator == first checks the size of both container, if sizes are same then it compares elements sequentially and comparison stops at first mismatch.

How do you find the size of a vector in C++? ›

CPP. size() function is used to return the size of the vector container or the number of elements in the vector container.

How do you fill a vector? ›

Vector Fills - How to Fill Vectors in Clip Studio Paint - YouTube

How do you initialize an entire array with value 1? ›

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

How do you initialize an empty array in C++? ›

Can I create an empty array in C ++? You can't create an array empty. An array has a fixed size that you can not change. If you want to initialize the array you can put the value as 0 to create an empty array but an array cant have 0 sizes.

How do you initialize all elements of an 2D array to 0 in C++? ›

Consider the array declaration – int array [M][N] = {1}; , which sets the element at the first column in the first row to 1 and all other elements to 0. We can use this trick to explicitly initialize only the first element of the array with 0, causing the remaining elements to be initialized with zeroes automatically.

How do you initialize a vector with all values 0? ›

You can use: std::vector<int> v(100); // 100 is the number of elements. // The elements are initialized with zero values.

How do you find the elements of a vector? ›

Vector elements are accessed using indexing vectors, which can be numeric, character or logical vectors. You can access an individual element of a vector by its position (or "index"), indicated using square brackets. In R, the first element has an index of 1. To get the 7th element of the colors vector: colors[7] .

How do you set a vector value to zero? ›

A vector can be initialized with all zeros in three principal ways: A) use the initializer_list, B) use the assign() vector member function to an empty vector (or push_back()), or C) use int or float as the template parameter specialization for a vector of initially only default values.

Which is used to use a function from one source file to another? ›

7. Which is used to use a function from one source file to another? Explanation: By defining a function's prototype in another file means, we can inherit all the features from the source function. 8.

Is a vector an array C++? ›

Vectors in C++ are the dynamic arrays that are used to store data. Unlike arrays, which are used to store sequential data and are static in nature, Vectors provide more flexibility to the program.

How many vector container properties are there in C++? ›

Explanation: There are three container properties in c++. They are sequence, Dynamic array and allocator-aware.

How do I convert a string to an int in C++? ›

Using the stoi() function

The stoi() function converts a string data to an integer type by passing the string as a parameter to return an integer value. The stoi() function contains an str argument. The str string is passed inside the stoi() function to convert string data into an integer value.

What is map used for in C++? ›

What is a map in C++? A C++ map is a way to store a key-value pair. A map can be declared as follows: #include <iostream> #include <map> map<int, int> sample_map; Each map entry consists of a pair: a key and a value.

How do you define a constructor in C++? ›

  1. Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation. ...
  2. Example.
  3. Example.
22 Aug 2022

Can we change elements of a vector? ›

An element in a Vector can be replaced at a specified index using the java. util. Vector. set() method.

Can you edit a pair in C++? ›

In C++, a set is an associative container that holds unique objects. Once you apply an aspect to a specific, you cannot change it. To modify them, one can only delete and add components. C++ pair is a type that is specified under the utility> header and is used to connect two pair values.

How do I change the value of a vector at a specific index? ›

An element in the vector can be replaced at a particular/specified index with another element using set() method, or we can say java. util. Vector. set() method.

How do you add two vectors in C++? ›

Given two vectors, join these two vectors using STL in C++. Approach: Joining can be done with the help of set_union() function provided in STL. Syntax: set_union (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result);

Why is vector used in C++? ›

In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library.

Is a vector a list? ›

A list holds different data such as Numeric, Character, logical, etc. Vector stores elements of the same type or converts implicitly. Lists are recursive, whereas vector is not. The vector is one-dimensional, whereas the list is a multidimensional object.

What is a vector PDF? ›

A vector-based PDF uses line segments to define all of the geometry on the page. Most PDFs created from CAD (Computer-Aided Design) are vector-based. Vector PDFs are usually preferred to raster PDFs because they contain more data that make it easier to work with.

How do I edit an image in Illustrator? ›

How to edit and relink images in Illustrator - YouTube

What is a vector form? ›

Vector Form is used to represent a point or a line in a cartesian system, in the form of a vector. The vector form of representation helps to perform numerous operations such as addition, subtractions, multiplication of vectors.

What is initialization in C++ with example? ›

[edit] Initialization of a variable provides its initial value at the time of construction. The initial value may be provided in the initializer section of a declarator or a new expression. It also takes place during function calls: function parameters and the function return values are also initialized.

What is meant by initialization in C++? ›

In computer programming, initialization (or initialisation) is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized.

How do you declare and initialize a constant in C++? ›

A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .

How do you assign a value to a 2d vector in C++? ›

Initialize a two-dimensional vector in C++
  1. Using Fill Constructor. The recommended approach is to use a fill constructor to initialize a two-dimensional vector. ...
  2. Using resize() function. The resize() function is used to resize a vector to the specified size. ...
  3. Using push_back() function. ...
  4. Using Initializer Lists.

Which statement correctly uses C ++ 11 to initialize a vector of ints named n with the values 10 and 20? ›

Which statement correctly uses C++ 11 to initialize a vector of ints named n with the values 10 and 20? It creates a vector object with a starting size of 10.

How do you initialize a string to null in C++? ›

We can do this using the std::string::clear function. It helps to clear the whole string and sets its value to null (empty string) and the size of the string becomes 0 characters. string::clear does not require any parameters, does not return any error, and returns a null value.

How do you remove a character from a string in C++? ›

In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed.

How do you declare a word in C++? ›

It is not possible to declare a word in C++. The word-length varies from machine to machine. Often a "short int" is a word, but one cannot be sure. If you're using Win API, there's a type called WORD.

How do you initialize a vector with a specific size? ›

To initialize a two-dimensional vector to be of a certain size, you can first initialize a one-dimensional vector and then use this to initialize the two-dimensional one: vector<int> v(5); vector<vector<int> > v2(8,v); or you can do it in one line: vector<vector<int> > v2(8, vector<int>(5));

How do you initialize a map in C++? ›

Let's see the different ways to initialize a map in C++.
  1. Initialization using assignment and subscript operator.
  2. Initialization using an initializer list.
  3. Initialization using an array of pairs.
  4. Initialization from another map using the map.insert() method.
  5. Initialization from another map using the copy constructor.
13 Apr 2022

How do you take the input of a vector? ›

The basic way is if the user will give the size of the vector then we can take input into vector simply using for loop. See the code below to understand it better. Example code 2 : If the user will not enter the size of the vector but the user wants to enter vector elements as much as they want.

Which statement correctly uses C ++ 11 to initialize a vector of ints named n with the values 10 and 20? ›

Which statement correctly uses C++ 11 to initialize a vector of ints named n with the values 10 and 20? It creates a vector object with a starting size of 10.

How do you initialize a variable in C++? ›

Variable initialization in C++

There are two ways to initialize the variable. One is static initialization in which the variable is assigned a value in the program and another is dynamic initialization in which the variables is assigned a value at the run time.

How do I get the size of a vector in C++? ›

vector::size()

size() function is used to return the size of the vector container or the number of elements in the vector container.

What is the default value of vector in C++? ›

The default value of a vector is 0.

How do I convert a string to an int in C++? ›

Using the stoi() function

The stoi() function converts a string data to an integer type by passing the string as a parameter to return an integer value. The stoi() function contains an str argument. The str string is passed inside the stoi() function to convert string data into an integer value.

What is map used for in C++? ›

What is a map in C++? A C++ map is a way to store a key-value pair. A map can be declared as follows: #include <iostream> #include <map> map<int, int> sample_map; Each map entry consists of a pair: a key and a value.

How do you define a constructor in C++? ›

  1. Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation. ...
  2. Example.
  3. Example.
22 Aug 2022

What is vector in C++ with example? ›

Vectors in C++ are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.

Can I compare two vectors C++? ›

The C++ function std::vector::operator== tests whether two vectors are equal or not. Operator == first checks the size of both container, if sizes are same then it compares elements sequentially and comparison stops at first mismatch.

How do you make a vector empty in C++? ›

clear() function is used to remove all the elements of the vector container, thus making it size 0.

Which is the correct statement about vector element declaration? ›

Explanation: The syntax for declaring the vector element is vector<type> variable_name (number_of_elements);

Is automatically appended to a character array when it is initialized with a string constant? ›

10 Cards in this Set
What is the last legal subscript that can be used with the following array? int values[5];4
A two-dimensional array can have elements of ________ data type(s).one
The ________ is automatically appended to a character array when it is initialized with a string constant.null terminator
7 more rows

What is the term used for the number inside the brackets of an array that specifies how many values the array can hold? ›

The size declarator is used in a definition of an array to indicate the number of elements the array will have. Look at the following array definition: int values [10];

Top Articles
Latest Posts
Article information

Author: Aracelis Kilback

Last Updated:

Views: 6324

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Aracelis Kilback

Birthday: 1994-11-22

Address: Apt. 895 30151 Green Plain, Lake Mariela, RI 98141

Phone: +5992291857476

Job: Legal Officer

Hobby: LARPing, role-playing games, Slacklining, Reading, Inline skating, Brazilian jiu-jitsu, Dance

Introduction: My name is Aracelis Kilback, I am a nice, gentle, agreeable, joyous, attractive, combative, gifted person who loves writing and wants to share my knowledge and understanding with you.