copy_n() Function in C++ STL
Last Updated :
27 Nov, 2022
Copy_n() is the C++ function defined in <algorithm> library in STL. It helps to copy one array element to the new array. Copy_n function allows the freedom to choose how many elements must be copied in the destination container. This function takes 3 arguments, the source array name, the size of the array, and the target array name.
Function Template:
template <class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n (InputIterator start_limit, Size count, OutputIterator result);
Parameters:
start_limit – Input iterator pointing to the beginning of the range of elements to copy from.
count – Number of elements to copy.
result – Output iterator to the initial position in the new container.
Time Complexity: O(n)
Auxiliary Space: O(n)
Example 1:
C++
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int ar[6] = { 8, 2, 1, 7, 3, 9 };
int ar1[6];
copy_n(ar, 6, ar1);
cout << "The new array after copying is : " ;
for ( int i = 0; i < 6; i++) {
cout << ar1[i] << " " ;
}
return 0;
}
|
Output
The new array after copying is : 8 2 1 7 3 9
Below is the code demonstrating the use of the copy_n() function for vectors.
Example 2:
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > v1 = { 8, 2, 1, 7, 3, 9 };
vector< int > v2(6);
copy_n(v1.begin(), 3, v2.begin());
cout << "The new vector after copying is : " ;
for ( int i = 0; i < v2.size(); i++) {
cout << v2[i] << " " ;
}
return 0;
}
|
Output
The new vector after copying is : 8 2 1 0 0 0
Share your thoughts in the comments
Please Login to comment...