pickzy.com

C  |  C++  |  Objective-C  |  VC++  |  Win32  |  MFC  |  Java  |  Php  |  Delphi  |  Visual Basic  |  .Net  |  Networking  |  General  |  Games  |  Jobs  |  Javascript  |  




Menu

pickSourcecode.com


        

 




 

Cpp > Programs

 

cpp vector example 4

#include <iostream>
#include <vector>
using namespace std;


typedef vector<int> intVector;


template<class T, class A>

void ShowVector(const vector<T, A>& v);
template<class T, class A>

void compareVectors(const vector<T, A>& v1, const vector<T, A>& v2);

int main()
{

intVector vInt1(5);
//  define  a  vector  of  integers  with  5  elements
cout << "vInt1(5)" << "\n";


//  assign  a  value  to  each  element  in  vInt  using  subscripts
for (vector<int>::size_type i = 0; i < vInt1.size(); ++i) {
vInt1[i] = 5 * i;

}

ShowVector(vInt1);


intVector vInt2 = vInt1;
//  define  a  vector  vInt2  and
//  copy  elements  from  vInt1
cout << "vInt2(5)" << "\n";

ShowVector(vInt2);


//  compare  vInt  and  vInt2
compareVectors(vInt1, vInt2);


//  add  an  element  at  the  end  of  vInt2
cout << "vInt2 after push_back()\n";

vInt2.push_back(100);

ShowVector(vInt2);


//  compare  vInt  and  vInt2  again
compareVectors(vInt1, vInt2);


//  now  swap  vInt  and  vInt2
vInt1.swap(vInt2);

cout << "vInt1 after swap\n";

ShowVector(vInt1);

cout << "vInt2 after swap\n";

ShowVector(vInt2);

compareVectors(vInt1, vInt2);


return 0;

}


//
//  Display  vector  properties
//
template<class T, class A>

void ShowVector(const vector<T, A>& v)
{

cout << "size() = " << v.size() << "\tcapacity() = " << v.capacity() << "\n";


//  display  vector  elements  using  subscripts
cout << "elements:\t";

for (vector<T, A>::size_type i = 0; i < v.size(); ++i)
cout << v[i] << ", ";

cout << "\n\n";

}


//
//  Compare  two  vectors
//
template<class T, class A>

void compareVectors(const vector<T, A>& v1, const vector<T, A>& v2)
{

if (v1 == v2) {
cout << "v1 == v2";

}

else 
if (v1 < v2)
{

cout << "v1 < v2";

}

else

{

cout << "v1 > v2";

}

cout << "\n\n";

}


 
Privacy Policy | About Us