7 ways to Initialize Vector in C++ - GeeksforGeeks (2024)

Last Updated : 01 Jul, 2024

Summarize

Comments

Improve

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++.

Table of Content

  • 1. Initializing Vector by Pushing values One by One
  • 2. Initializing Vector by Specifying Size and Initializing All Values
  • 3. Initializing Vector like Arrays
  • 4. Initializing Vector from an Array
  • 5. Initializing Vector from Another Vector
  • 6. Initializing all Elements of Vector with a Particular Value
  • 7. Initialize Vector with Consecutive Numbers using std::iota

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.



7 ways to Initialize Vector in C++ - GeeksforGeeks (1)

GeeksforGeeks

7 ways to Initialize Vector in C++ - GeeksforGeeks (2)

Improve

Previous Article

Vector in C++ STL

Next Article

vector::begin() and vector::end() in C++ STL

Please Login to comment...

7 ways to Initialize Vector in C++ - GeeksforGeeks (2024)

FAQs

7 ways to Initialize Vector in C++ - GeeksforGeeks? ›

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++? ›

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 a vector in memory? ›

“The Vectors are a topography of memory. They function as points in both space and time, while connecting to the story of liberation. It is important that the markers communicate a very clear and bold message.”

What is the internal implementation of a vector in C++? ›

A vector in C++ is implemented as a dynamic array at a high level. It allows you to store and modify elements in a contiguous memory block in a simple and flexible manner. Here's how it works on the inside: Std::vector allocates space on the heap and stores each of its components in a single contiguous chunk of memory.

How to define a vector? ›

A vector is an object that has both a magnitude and a direction. Geometrically, we can picture a vector as a directed line segment, whose length is the magnitude of the vector and with an arrow indicating the direction. The direction of the vector is from its tail to its head.

Do I need to initialize a vector in C++ class? ›

Since std::vector is a class type its default constructor is called. So the manual initialization isn't needed. You do not have to initialise it explcitly, it will be created when you create an instance of your class.

How to initialize a vector in C++ empty? ›

Here's how you can do it:
  1. #include <vector>
  2. int main() {
  3. std::vector<int> myVector; // This initializes an empty vector of integers.
  4. // You can now push elements into myVector using push_back() or other methods.
  5. return 0;
  6. }
Apr 18, 2022

How do you insert a vector into a vector of vectors in C++? ›

Insertion in Vector of Vectors

Elements can be inserted into a vector using the push_back() function of C++ STL. Below example demonstrates the insertion operation in a vector of vectors. The code creates a 2D vector by using the push_back() function and then displays the matrix.

Can I assign a vector to a vector C++? ›

Method 2: By assignment “=” operator. Simply assigning the new vector to the old one copies the vector. This way of assignment is not possible in the case of arrays.

How are vectors passed in C++? ›

However, to pass a vector there are two ways to do so:
  • Pass By value.
  • Pass By Reference.
Feb 27, 2024

Can you return a vector in C++? ›

Returning a vector as a pointer can be done by creating the vector on the heap within the function and returning its pointer. This way, the vector won't go out of scope when the function ends. However, it's important to remember to delete the vector when you're done with it to avoid memory leaks.

How do you initialize a vector with default values in C++? ›

To initialize a vector with default values in C++, the most straightforward way is to use the vector constructor that takes the size of the vector and the default value to initialize as arguments. The constructor function initializes the vector with the provided default value directly.

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

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.

How to initialize the array in C++? ›

An array can be initialized in the declaration by writing a comma-separated list of values enclosed in braces following an equal sign. int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};

How to initialize a 2D vector in C++? ›

In C++, you can initialize a 2D vector using the resize() function from the std::vector class. The resize() function allows you to specify the size of the 2D vector, and if needed, it also initializes the elements to a default value (0 for integers, 0.0 for doubles, etc.).

How to initialize a vector in C++ with set 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));

Top Articles
How to Invest in ABLE Accounts
Credit Cards for Free Travel & Cash Back - Physician on FIRE
PontiacMadeDDG family: mother, father and siblings
Davante Adams Wikipedia
How to change your Android phone's default Google account
Hk Jockey Club Result
Notary Ups Hours
Puretalkusa.com/Amac
Nwi Police Blotter
Barstool Sports Gif
Zachary Zulock Linkedin
Rainfall Map Oklahoma
Ncaaf Reference
Caroline Cps.powerschool.com
Goldsboro Daily News Obituaries
Items/Tm/Hm cheats for Pokemon FireRed on GBA
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
Adam4Adam Discount Codes
Craigslist Missoula Atv
Webcentral Cuny
Nearest Walgreens Or Cvs Near Me
Best Transmission Service Margate
Little Rock Skipthegames
Weve Got You Surrounded Meme
Craigslist Alo
Il Speedtest Rcn Net
Chicago Based Pizza Chain Familiarly
Die 8 Rollen einer Führungskraft
Pioneer Library Overdrive
Darknet Opsec Bible 2022
Planned re-opening of Interchange welcomed - but questions still remain
Learn4Good Job Posting
Bt33Nhn
1987 Monte Carlo Ss For Sale Craigslist
Amici Pizza Los Alamitos
M3Gan Showtimes Near Cinemark North Hills And Xd
Federal Student Aid
How to Play the G Chord on Guitar: A Comprehensive Guide - Breakthrough Guitar | Online Guitar Lessons
Why Gas Prices Are So High (Published 2022)
Craigslist Boats Dallas
11526 Lake Ave Cleveland Oh 44102
2007 Jaguar XK Low Miles for sale - Palm Desert, CA - craigslist
Tricia Vacanti Obituary
Doe Infohub
Tfn Powerschool
Yourcuteelena
Unit 11 Homework 3 Area Of Composite Figures
Xre 00251
Craigslist Chautauqua Ny
Here’s What Goes on at a Gentlemen’s Club – Crafternoon Cabaret Club
60 Second Burger Run Unblocked
Concentrix + Webhelp devient Concentrix
Latest Posts
Article information

Author: Kieth Sipes

Last Updated:

Views: 6729

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.