COPY()
This function is used to copy elements from one range to another. It takes three iterators as arguments: the beginning and end of the source range, and the beginning of the destination range. The function then sequentially copies each element from the source to the destination in order, preserving their original order. The destination range must be large enough to hold all copied elements, as std::copy() does not allocate new memory or check boundaries. It returns an iterator pointing to the element in the destination range just past the last copied element. Commonly used with arrays, vectors, or other STL containers, std::copy() provides an efficient, type-safe way to duplicate data and is often preferred over manual loops for readability and maintainability.
copy(begin, end, destination);
* begin: The starting point of the source range (inclusive).
* end: The ending point of the source range (exclusive).
* destination: The beginning of the destination where the copied elements will
be stored.#include <iostream>
#include <algorithm> // For copy
using namespace std;
int main() {
// Source array
int source[] = {1, 2, 3, 4, 5};
// Destination array with the same size
int destination[5];
// Copy elements from source to destination using copy
// (source + 5) moves that pointer forward by 5 elements; that is, source + 5
// points to the memory address right after source[4].
// Start copying from source[0]; Stop before source[5] (which doesn’t exist — it’s just the sentinel marking the end)
copy(source, source + 5, destination);
// Output the copied elements in destination
cout << "Destination array: ";
for (int i = 0; i < 5; i++) {
cout << destination[i] << " ";
}
cout << endl;
return 0;
}
OUTPUT:
Destination array: 1 2 3 4 5Last updated