In C++, a vector is a dynamic array-like data structure provided by the Standard Template Library (STL). It allows the storage of elements of the same type in a contiguous memory block and provides dynamic resizing, allowing elements to be added or removed efficiently.
Vectors also support random access to elements and offer a variety of useful member functions for manipulation and iteration. There are multiple ways to initialize a vector and here we are going to see 5 different ways to do so. Let's learn each of them one by one.
1. Initializing with Initializer List:
//C++ Program to initialize vector using initializer #include<iostream> #include<vector> using namespace std; int main(){ vector<int> nums = {1, 2, 3, 4, 5}; for(int it : nums){ cout<< it << " "; } return 0; }
1 2 3 4 5
2. Initializing using push_back() function:
It is a built-in function present in the vector used to push the element at the end. Read more to know about vector built-in functions.
//C++ Program to initialize vector one by one #include<iostream> #include<vector> using namespace std; int main(){ vector<int> nums; nums.push_back(1); nums.push_back(2); nums.push_back(8); nums.push_back(0); for(int it : nums){ cout<< it << " "; } return 0; }
1 2 8 0
3. Initializing with Size and Default Value:
//C++ Program to initialize vector by default value #include<iostream> #include<vector> using namespace std; int main(){ //vector of size 5 with all elements initialized to 0 vector<int> nums(5, 0); for(int it : nums){ cout<< it << " "; } return 0; }
0 0 0 0 0
4. Initializing with Range of Elements:
//C++ Program to initialize one vector using another vector #include<iostream> #include<vector> using namespace std; int main(){ vector<int> nums{7, 2, 3, 1, 5}; // Create a new vector with the same elements as nums vector<int> copyNums(nums.begin(), nums.end()); for(int it : copyNums){ cout<< it << " "; } return 0; }
7 2 3 1 5
5. Initializing with Array:
//C++ Program to initialize one vector using array #include<iostream> #include<vector> using namespace std; int main(){ int arr[] = {1, 2, 3, 4, 5}; //size of given array int n = sizeof(arr) / sizeof(arr[0]); vector<int> nums(arr, arr + n); for(int it : nums){ cout<< it << " "; } return 0; }
7 2 3 1 5
No comments:
Post a Comment