Wednesday, 27 April 2011

Example of Algorithm Copy

Sometimes its useful to know the 'copy' method in algorithm class. The following is an example:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

//OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result );

#include<iostream>
#include <algorithm>
#include <vector>

using namespace
std;

int
main()
{

int
someInts[] = {10, 20, 20, 40, 50};
int
someMoreInts[] = {100, 200, 300, 400, 500, 600, 700};

vector<int> someVector;
vector<int>::iterator someIterator;

//Get the total size of all elements
int totalSize = (sizeof(someInts) + sizeof(someMoreInts)) / sizeof(int);

//Resize someVector to right size
someVector.resize(someVector.size() + totalSize);

//Get the number of elements of someInts
int tempSize = sizeof(someInts) / sizeof(int);

vector<int>::iterator finalElementIt = copy(someInts, someInts + tempSize, someVector.begin());

cout<<"\n1. someVector contains :";
for
(someIterator = someVector.begin(); someIterator != someVector.end(); ++someIterator)
cout<<" "<<*someIterator;
cout<<endl;

//Get size of someMoreInts
tempSize = sizeof(someMoreInts) / sizeof(int);

copy(someMoreInts, someMoreInts + tempSize, finalElementIt);

cout<<"\n2. someVector contains :";
for
(someIterator = someVector.begin(); someIterator != someVector.end(); ++someIterator)
cout<<" "<<*someIterator;
cout<<endl;

return
0;
}


The output is as follows:

No comments:

Post a Comment