Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Vector end() in C++ STL
Next article icon

8 Ways to Initialize Vector in C++

Last Updated : 06 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Initializing a vector means assigning some initial values to the std::vector elements. In this article, we will learn 8 different ways to initialize a vector in C++.

Table of Content

  • Using Initializer List
  • One by One Initialization
  • With a Single Value
  • From an Array
  • From Another Vector
  • From Any STL Container
  • Using std::fill() Function
  • Using std::iota() Function

Using Initializer List

We can initialize a vector with the list of values enclosed in curly braces {} known as initializer list. The values of the list will be assigned sequentially i.e. 1st value will be assigned to the 1st element of vector, 2nd value to 2nd element and so on.

Syntax

vector<type> v = {val1, val2, val3,...};

where, val1, val2, val3,... are the initial values.

Example

C++
// C++ Program to initializ std::vector with // initializer list #include <bits/stdc++.h> using namespace std;  int main() {      // Initializing std::vector with list of     // multiple values     vector<int> v = {11, 23, 45, 89};      for (auto i : v)         cout << i << " ";     return 0; } 

Output
11 23 45 89 

One by One Initialization

Vector can be initialized by pushing value one by one. In this method, an empty vector is created, and elements are added to it one by one using the vector::push_back() method. This method is mostly used to initialize vector after declaration.

Syntax

v.push_back(val);

where, val is the value which we have to insert.

Example

C++
// C++ Program to initialize std::vector by // pushing values one by one #include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v;      // Pushing Value one by one     v.push_back(11);     v.push_back(23);     v.push_back(45);     v.push_back(89);      for (auto i : v)         cout << i << " ";     return 0; } 

Output
11 23 45 89 

With a Single Value

We can initialize all the elements of the vector to a single value. We create a vector of a specified size and initialize all elements to the same value using vector constructor.

Syntax

vector<type> v(n, val);

where, n is the size and val is the initial value.

Example

C++
// C++ Program to initializ the std::vector // with specific value #include <bits/stdc++.h> using namespace std;  int main() {      // Initializing all the elements of a   	// vector using a single value     vector<int> v(5, 11);      for (auto i : v)         cout << i << " ";     return 0; } 

Output
11 11 11 11 11 

From an Array

We can also initialize a vector using plain old static arrays using vector constructor. This works by copying all the elements of the array to the newly created vector.

Syntax

vector<type> v(arr, arr + n);

where arr is the array name and n is the size of the array.

Example

C++
// C++ Program to initializ the std::vector // from another array #include <bits/stdc++.h> using namespace std;  int main() {     int arr[] = {11, 23, 45, 89};     int n = sizeof(arr) / sizeof(arr[0]);      // Initialize the std::vector v by arr     vector<int> v = {arr, arr + n};      for (auto i : v)         cout << i << " ";     return 0; } 

Output
11 23 45 89 

From Another Vector

We can also initialize a newly created vector from an already created vector if they are of same type.

Syntax

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

where v1 is the already existing vector.

Example

C++
// C++ Program to initializ the std::vector // from another vector #include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v1 = {11, 23, 45, 89};      // Initialize the vector v2 from vector v1     vector<int> v2(v1.begin(), v1.end());      for (auto i : v2)         cout << i << " ";     return 0; } 

Output
11 23 45 89 

From Any STL Container

Vectors are flexible containers that can be initialized by any other already existing containers such as set, multiset, map, etc. if they are of same type.

Syntax

vector<type> v(first, last);

where first and last are the iterator to the first element and the element just after the last element in the range of STL container.

Using std::fill() Function

We can also use the std::fill function to initialize the whole or a part of a vector to the same value.

Syntax

fill(first, last, val);

where first and last are the iterator to the first element and the element just after the last element in the range of STL container and val is the value to be initialized with.

Example

C++
// C++ Program to initialize the std::vector // using std::fill() method #include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v(5);      // Initialize vector v with 11     fill(v.begin(), v.end(), 11);      for (auto i : v)         cout << i << " ";     return 0; } 

Output
11 11 11 11 11 

Using std::iota() Function

The std::iota() function from the <numeric> library allows us to initialize a vector with consecutive values starting from the given value.

Syntax

std::iota(first, last, val);

where first and last are the iterator to the first element and the element just after the last element in the range of the vector and val refers to the starting value.

Example

C++
// C++ Program to initializ the std::vector // using std::iota() #include <bits/stdc++.h> using namespace std;  int main() {     vector<int> v(5);      // Using std::iota() to initialize vector v   	// with 11     iota(v.begin(), v.end(), 11);      for (auto i : v)         cout << i << " ";     return 0; } 

Output
11 12 13 14 15 



Next Article
Vector end() in C++ STL

K

Kartik
Improve
Article Tags :
  • Misc
  • C++
  • STL
  • cpp-vector
Practice Tags :
  • CPP
  • Misc
  • STL

Similar Reads

  • Vector in C++ STL
    C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted. Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template
    8 min read
  • 8 Ways to Initialize Vector in C++
    Initializing a vector means assigning some initial values to the std::vector elements. In this article, we will learn 8 different ways to initialize a vector in C++. Table of Content Using Initializer ListOne by One InitializationWith a Single ValueFrom an ArrayFrom Another VectorFrom Any STL Contai
    5 min read
  • Commonly Used Methods

    • Vector end() in C++ STL
      In C++, the vector end() is a built-in method used to obtain an iterator pointing to the theoretical element after the last element of the vector. Even though this iterator does not point to a valid element, it serves as a marker for the end of the vector. Let’s take a look at an example that illust
      4 min read

    • Vector empty() in C++ STL
      In C++, vector empty() is a built-in method used to check whether the given vector is empty or not. In this article, we will learn about vector empty() method in C++. Let’s take a look at an example that illustrates the vector empty() method: [GFGTABS] C++ #include <bits/stdc++.h> using namesp
      2 min read

    • Vector operator[ ] in C++ STL
      In C++, the vector operator [] is used to randomly access or update the elements of vector using their indexes. It is similar to the vector at() function but it doesn't check whether the given index lies in the vector or not. Let’s take a look at a simple code example: [GFGTABS] C++ #include <bit
      3 min read

    • Vector front() in C++ STL
      In C++, the vector front() is a built-in function used to retrieve the first element of the vector. It provides a reference to the first element, allowing you to read or modify it directly. Let’s take a quick look at a simple example that uses the vector front() method: [GFGTABS] C++ #include <bi
      2 min read

    • Vector push_back() in C++ STL
      In C++, the vector push_back() is a built-in method used to add a new element at the end of the vector. It automatically resizes the vector if there is not enough space to accommodate the new element. Let’s take a look at an example that illustrates the vector push_back() method: [GFGTABS] C++ #incl
      2 min read

    • Vector insert() in C++ STL
      In C++, the vector insert() is a built-in function used to insert new elements at the given position in a vector. In this article, we will learn about the vector insert() function in C++. Let’s take a look at an example that shows the how to use this function: [GFGTABS] C++ #include <bits/stdc++.
      5 min read

    • vector emplace() in C++ STL
      In C++, vector emplace() is used to insert elements at the given position in a vector by constructing it in-place within the vector, rather than creating a temporary object and then moving or copying it into the vector. Let's take a quick look at a simple example that uses vector emplace() method: [
      4 min read

    • Vector assign() in C++ STL
      In C++, the vector assign() is a built-in method used to assign the new values to the given vector by replacing old ones. It also modifies the size of the vector according to the given number of elements. Let’s take a look at an example that shows the how to use this function. [GFGTABS] C++ #include
      4 min read

    • Vector erase() in C++ STL
      In C++, vector erase() is a built-in function that is used to delete elements from the vector. It removes an element of a specific position or range of elements from the vector. Let’s take a simple example that uses the vector erase() method: [GFGTABS] C++ #include <bits/stdc++.h> using namesp
      3 min read

    Other Member Methods

    • Vector max_size() in C++ STL
      In C++, vector max_size() is a built-in function used to find the maximum number of elements that can be held by the vector container. In this article, we will learn about the vector max_size() function in C++. Let's take a look at an example that illustrates this method: [GFGTABS] CPP #include <
      3 min read

    • Vector capacity() in C++ STL
      In C++, the vector capacity() is a built-in method used to find the capacity of vector. The capacity indicates how many elements the vector can hold before it needs to reallocate additional memory. In this article, we will learn about vector capacity() method in C++. Let’s take a look at an example
      3 min read

    • vector rbegin() and rend() Functions in C++ STL
      In C++, std::vector::rbegin() and std::vector::rend() are built-in functions used to retrieve reverse iterators to the reverse beginning and reverse end of a vector. These functions allow easy traversal of vectors in reverse i.e. from the last element to the first. They are the member functions of t
      3 min read

    • vector :: cbegin() and vector :: cend() in C++ STL
      Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. vector::cbegin() The function returns an iterator which is used to iterate container. The iterator points to the beginning of the vector.Iterat
      2 min read

    • Vector crend() in C++ STL
      In C++, the vector crend() is a built-in method used to obtain a constant reverse iterator pointing to the theoretical element just before the first element of the vector. It is used to mark the reverse end of the vector. Let’s take a look at an example: [GFGTABS] C++ #include <bits/stdc++.h>
      2 min read

    • Vector resize() in C++ STL
      In C++, the vector resize() is a built-in method used to change the size of vector container after it is declared. It can be used to increase or decrease the size of vector. Let’s take a look at an example that illustrates the vector resize() method: [GFGTABS] C++ //Driver Code Starts{ #include <
      3 min read

    • Vector shrink_to_fit() in C++ STL
      In C++, vector shrink_to_fit() is a built-in function used to reduce the capacity of the vector to fit its size and destroys all elements beyond the size. In this article we will learn about vector shrink_to_fit() in C++. Let’s take a quick look at an example that illustrates vector shrink_to_fit()
      2 min read

    • When to use Vector reserve() in C++?
      In a vector, when the number of elements to be inserted are greater than the current capacity, it is reallocated to a larger memory block and all the items are copied to this new block making this reallocation an expensive operation with time complexity of O(n). This mechanism works well if you don'
      2 min read

    • Vector data() in C++ STL
      In C++, the vector data() is a built-in function used to access the internal array used by the vector to store its elements. In this article, we will learn about vector data() in C++. Let’s take a look at an example that illustrates the vector data() method: [GFGTABS] C++ #include <bits/stdc++.h
      2 min read

  • 2D Vector in C++
    A 2D vector is a vector of the vector i.e. each element is a vector in itself. It can be visualised as a matrix where each inner vector represents a row, and the number of rows represents the maximum columns. A 2D vector is dynamically resizable in both dimensions. Let’s take a look at a simple illu
    6 min read
  • Passing Vector to a Function in C++
    To perform operations on vector belonging to one function inside other function, we pass this vector to the function as arguments during the function call. C++ provides three methods to pass a vector to a function in C++. Let's look at each of them one by one. Table of Content Pass Vector by ValuePa
    5 min read
  • How Does a Vector Internally Works in C++?
    In C++, a vector is a dynamic array that can resize itself when more elements are added or deleted. So, one may ask that how a vector internally works to achieve its dynamic resizing capability while maintaining similar efficiency to static arrays in operations? For vector to work as a resizable dyn
    5 min read
  • How to implement our own Vector Class in C++?
    The given task is to implement a class in C++ which behaves just like the Vector class.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 elements a
    5 min read
  • Advantages of Vector Over Array in C++
    In C++, both vectors and arrays are used to store collections of elements, but vector offers significant advantages over arrays in terms of flexibility, functionality, and ease of use. This article explores the benefits of using vectors in C++ programming. The major advantages of vector over arrays
    3 min read
  • Common Vector Programs

    • Sorting a Vector in C++
      Sorting a vector means arranging the elements of vector in ascending order or in descending order or in desired defined order. In this article, we will learn about different ways to sort the vector in C++. The most efficient way to sort the vector is by using sort() method. Let’s take a look at an e
      3 min read

    • How to Reverse a Vector using STL in C++?
      Reversing the vector means the swapping last element and first element, second last element and second element, and so on. In this article, we will learn how to reverse a vector using STL in C++. The most efficient method to reverse the vector is by using reverse() function. Let’s take a look at a s
      3 min read

    • How to Find the Minimum and Maximum Element of a Vector Using STL in C++?
      In this article, we will learn how to find the minimum and maximum element in vector in C++. The simplest method to find the minimum and maximum element in vector is by using min_element() and max_element(). Let’s take a look at a simple example: [GFGTABS] C++ #include <bits/stdc++.h> using na
      2 min read

    • How to Find Index of a Given Element in a Vector in C++?
      Vectors stores elements in contiguous memory and these elements can be accessed by their indexes. In this article, we will learn the reverse process, i.e., finding the index of the given element in a vector in C++. The simplest way to find the index of the given element in the vector is by using fin
      3 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences