Why is my vector program kept on crashing
There's the question:
5. Use C++ Standard Template Library <vector> to do the followings:
(a) Declare a vector named v1 of type int.
(b) Use function push_back() to store value 1, 2, 3 and 4 into v1.
(c) Print out the size of v1.
(d) Use a for loop to print out each element value of v1.
(e) Assign a new value 5 to element 1.
(f) Remove the last element.
(g) Print out all elements of v1 using an iterator named it to access each element of v1.
(h) Insert new element value 10 at position 0 (the first element).
(i) Use erase() to remove element at position 2.
(j) Use a for loop to print out each element value of v1 again.
(k) Remove all the elements in the vector v1.
(l) Check if the vector v1 is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector <int> vl;
for(int i=1;i<=4;i++)
{
vl.push_back(i);
}
cout<<"Vector size= "<<vl.size()<<endl;
for(int i=0;i<vl.size();i++)
{
cout<<"Value of vl["<<i<<"]: "<<vl[i]<<endl;
}
cout<<endl;
vl.assign(1,5);
for(int i=0;i<vl.size();i++)
{
cout<<"Value of vl["<<i<<"]: "<<vl[i]<<endl;
}
cout<<endl;
vl.pop_back();
vector<int>::iterator it;
for(it=vl.begin();it!=vl.end();++it)
{
cout<<"Value of vector: "<<*it<<" ";
}
cout<<endl;
vl.insert(vl.begin(),10);
vl.erase(vl.begin()+2);
for(int i=0;i<vl.size();i++)
{
cout<<"Value of vl["<<i<<"]: "<<vl[i]<<endl;
}
vl.clear();
if(vl.empty()==true)
{
cout<<"\nThe vector vl is empty."<<endl;
}
else if(vl.empty()==false)
{
cout<<"\nThe vector vl isn't empty."<<endl;
}
return 0;
}
|