Sunday 8 March 2009

More on Vector Manipulation

This is slightly advanced vector manipulation program


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows advanced vector manipulation
#include<iostream>
#include<vector>

using namespace
std;

//This method prints the vector
void printer(vector<int> v)
{

unsigned int
i;
cout << "Size = " << v.size() << endl;
cout << "Contents = ";
for
(i = 0; i <v.size(); i++)
cout<<v[i]<<" ";
cout<<endl;
}


//Overloaded method same as above but takes pointers
void printer(vector<int*> v)
{

unsigned int
i;
cout << "\nOverloaded Method " << endl;
cout << "Size = " << v.size() << endl;
cout << "Contents = ";
for
(i = 0; i <v.size(); i++)
cout<<*v[i]<<" ";
cout<<endl;
}


int
main()
{

vector<int> v1(5, 1);
cout<<"** Original **"<<endl;
printer(v1);

unsigned int
i;
//Modifying the list above
for(i = 0; i < v1.size(); i++)
v1[i] = i + 3;
cout<<"\n** Modified **"<<endl;
printer(v1);

vector<int>::iterator it;
//Inserting in the list after the first element '0' and after the 4th elem '9 9 9 9'
it = v1.begin();
it += 1;
v1.insert(it,0);
it = v1.begin(); //Crash if you dont do this
it += 5; //Because we inserted '0', 4th element has become 5th.
v1.insert(it, 4, 9);
cout<<"\n** After Insert **"<<endl;
printer(v1);

//Testing Pop back - removes element from the end
v1.pop_back();
v1.pop_back();
cout<<"\n** After couple of Pop back's **"<<endl;
printer(v1);

//New Vector
cout<<endl<<"\n********** NEW *************"<<endl;
vector<int*> v2;
int
*a=new int(5);
int
*b=new int(6);
int
*c=new int(7);
int
*d=new int(11);
v2.push_back(a);
v2.push_back(b);
v2.push_back(c);
printer(v2);
cout<<"\ntwo pop_back and a push_back"<<endl;
v2.pop_back();
v2.pop_back();
v2.push_back(d);
printer(v2);
cout<<"\nClear Vector two"<<endl;
v2.clear();
printer(v2);

return
0;
}




The output is as follows:

No comments:

Post a Comment