c++
how to add elements to vector in c++
In this, we talked about declaring a vector and how to store elements in a vector by using push_back function
#include <bits/stdc++.h>
using namespace std;
int main() {
cout<<"Enter Number of elements in your vector: ";
int n;
cin>>n;
vector<int> v; // creating the vector (vector syntax)
cout<<"Enter the "<<n<<" elements in the vector: ";
for(int i=0;i<n;i++)
{
int temp;
cin>>temp;
v.push_back(temp); // push_back function is used to push elements to the back
}
cout<<"The entered elements in vector are : ";
for(int i=0;i<n;i++)
{
cout<<v[i]<<" ";
}
return 0;
}
Output
Enter Number of elements in your vector: 5
Enter the 5 elements in the vector: 1 2 3 4 5
The entered elements in the vector are: 1 2 3 4 5
Enter the 5 elements in the vector: 1 2 3 4 5
The entered elements in the vector are: 1 2 3 4 5
how to run the code in c++ :
save the code with the file name as file_name.cpp and compile the code as g++ file_name.cpp and run it is as ./a.out
Was this helpful?
Similar Posts