home | help
std::copy_backward(3)	       C++ Standard Libary	   std::copy_backward(3)

NAME
     std::copy_backward - std::copy_backward

Synopsis
	Defined in header <algorithm>
	template< class BidirIt1, class BidirIt2 >
	BidirIt2  copy_backward( BidirIt1 first, BidirIt1 last,       (constexpr
     since C++20)
	BidirIt2 d_last );

	Copies the elements from the range [first, last) to another range ending
     at d_last.
	The elements are copied in reverse order (the  last  element  is  copied
     first), but
	their relative order is preserved.

	The  behavior  is undefined if d_last is within (first, last]. std::copy
     must be used
	instead of std::copy_backward in that case.

Parameters
	first, last	 -	the range of the elements to copy from
	d_last		 -	the end of the destination range

Type requirements
	-
	BidirIt must meet the requirements of LegacyBidirectionalIterator.

Return value
	Iterator to the last element copied.

Complexity
	Exactly std::distance(first, last) assignments.

Notes
	When copying overlapping ranges, std::copy is appropriate  when  copying
     to the left
	(beginning of the destination range is outside the source range) while
	std::copy_backward  is appropriate when copying to the right (end of the
     destination
	range is outside the source range).

Possible implementation
	template<class BidirIt1, class BidirIt2>
	BidirIt2 copy_backward(BidirIt1 first, BidirIt1 last, BidirIt2 d_last)
	{
	    while (first != last)
		*(--d_last) = *(--last);
	    return d_last;
	}

Example
     // Run this code

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

      int main()
      {
	  std::vector<int> source(4);
	  std::iota(source.begin(), source.end(), 1); // fills with 1, 2, 3, 4

	  std::vector<int> destination(6);

	  std::copy_backward(source.begin(), source.end(), destination.end());

	  std::cout << "destination contains: ";
	  for (auto i: destination)
	      std::cout << i << ' ';
	  std::cout << '\n';
      }

Output:
      destination contains: 0 0 1 2 3 4

	Defect reports

	The following behavior-changing defect	reports  were  applied	retroac-
     tively to
	previously published C++ standards.

	   DR	  Applied  to		 Behavior as published		    Cor-
     rect behavior
			    1. the behavior was well-defined if d_last
	LWG 1206 C++98	    == last					1.  made
     undefined
			    2.	the behavior was undefined if d_last ==  2. made
     well-defined
			    first

See also
	copy		      copies a range of elements to a new location
	copy_if 	      (function template)
	(C++11)
	ranges::copy_backward copies a range of elements in backwards order
	(C++20) 	      (niebloid)

http://cppreference.com 	   2024.06.10		   std::copy_backward(3)

home | help