# Thread: copy algorithm

1. ## copy algorithm

I need help (explanation and examples) in understanding the copy algorithm.
Code:
```copy(InputIterator sourceBeg, InputIterator sourceEnd,
OutputIterator destBeg)```
Can the InputIterators be incremented like
Code:
```copy(InputIterator sourceBeg+1, InputIterator sourceEnd,
OutputIterator destBeg)```
This algorithm only works with/on vectors, correct?
Would you need to declare your input and output iterators like this:
Code:
```string::iterator start=source.begin();
string::iterator end=source.end();
string::iterator begin=dest.begin();```

2. Code:
```#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
vector<int> IntVect;
for( int j = 0; j < 10; ++j )
IntVect.push_back(j);

copy( IntVect.begin(), IntVect.end(), ostream_iterator<int>(cout,"\n") );

return 0;
}```
Outputs via cout:
0
1
2
3
4
5
6
7
8
9

You can use this to copy a vector container into a list container for example...
Code:
```#include <vector>
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;

int main()
{
vector<int> IntVect;
list<int> IntList;

for( int j = 0; j < 10; ++j )
IntVect.push_back(j);

// Copy contents of IntVect into IntList.

copy( IntVect.begin(), IntVect.end(), back_inserter(IntList) );

return 0;
}```
Noticed some ';' that I needed to make ','. Sory for any confusion.[/edit]

3. Note the std::back_inserter in
hk_mp5kpdw's code. That in place of IntList.end() prevents overrunning the bounds of IntList.

4. Code:
```#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
vector<int> IntVect;
for( int j = 0; j < 10; ++j )
IntVect.push_back(j);

copy( IntVect.begin(), IntVect.end(), ostream_iterator<int>
(cout,"\n") );  // I get errors here, see below

return 0;
}```
When I try this, I get the following errors:
E2451 undefined symbol 'ostream_interator'
and,
E2188 Expression Syntax

where the copy algorithm is used. see note in code above.
my compiler is Borland c++ builder 6.

5. Include iterator.
Code:
`#include <iterator>`

Popular pages Recent additions