Algorithm Copy Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Copy Function

Algorithm Copy Function

BLUF: Mastering Algorithm Copy Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Copy Function

C++ is renowned for its efficiency. Learn how Algorithm Copy Function enables low-level control and high-performance computing in the tutorial below.

The copy function in C++ Algorithm is employed to duplicate all the elements within the container [first, last] to another container beginning from the position specified as result.

Syntax

Example

template<class InputIterator, class OutputIterator>OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result);

Parameter

It serves as an input iterator pointing to the initial element within the specified range, with the element itself being encompassed within the range.

The final: Serving as an input iterator pointing to the concluding element within the range, excluding the element itself from the range.

It serves as an output iterator pointing to the initial element of the fresh container where the elements are duplicated.

Return value

An iterator pointing to the final element of the fresh range that starts with the result is provided.

Example 1

Example

#include<iostream>
#include<algorithm>
#include<vector>
int main()
{
	int newints[]={15,25,35,45,55,65,75};
	std::vector<int> newvector(7);
	std::copy (newints, newints+7, newvector.begin());
	std::cout <<"newvector contains:";
	for (std::vector<int>::iterator ti= newvector.begin(); ti!=newvector.end(); ++ti)
	std::cout<<" " <<*ti;
	std::cout<<"\n";
	return 0;
}

Output:

Output

newvector contains: 15 25 35 45 55 65 75

Complexity

The function's complexity increases linearly as it progresses from the initial element to the final element.

Data races

Some or all of the container objects are accesed.

Exceptions

The function will raise an exception if any of the container elements also raises an exception.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience