Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/copy"

From cppreference.com
< cpp‎ | algorithm
m (missed return type)
m (Minor tweak.)
 
(33 intermediate revisions by 17 users not shown)
Line 2: Line 2:
 
{{cpp/algorithm/navbar}}
 
{{cpp/algorithm/navbar}}
 
{{dcl begin}}
 
{{dcl begin}}
{{dcl header | algorithm}}
+
{{dcl header|algorithm}}
{{dcl | since= | num= 1 |1=  
+
{{dcla|num=1|notes={{mark constexpr since c++20}}|
 
template< class InputIt, class OutputIt >
 
template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last, OutputIt d_first );
+
OutputIt copy( InputIt first, InputIt last,
 +
              OutputIt d_first );
 
}}
 
}}
{{dcl | since=c++17 | num= 2 |1=
+
{{dcl|num=2|since=c++17|
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
+
template< class ExecutionPolicy,
ForwardIt2 copy( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first );}}
+
          class ForwardIt1, class ForwardIt2 >
{{dcl | since=c++11 | num= 3 |1= 
+
ForwardIt2 copy( ExecutionPolicy&& policy,
template< class InputIt, class OutputIt, class UnaryPredicate >
+
                ForwardIt1 first, ForwardIt1 last,
 +
                ForwardIt2 d_first );
 +
}}
 +
{{dcla|num=3|since=c++11|notes={{mark constexpr since c++20}}|
 +
template< class InputIt, class OutputIt, class UnaryPred >
 
OutputIt copy_if( InputIt first, InputIt last,
 
OutputIt copy_if( InputIt first, InputIt last,
                   OutputIt d_first,
+
                   OutputIt d_first, UnaryPred pred );
                  UnaryPredicate pred );
+
}}
 +
{{dcl|num=4|since=c++17|1=
 +
template< class ExecutionPolicy,
 +
          class ForwardIt1, class ForwardIt2, class UnaryPred >
 +
ForwardIt2 copy_if( ExecutionPolicy&& policy,
 +
                    ForwardIt1 first, ForwardIt1 last,
 +
                    ForwardIt2 d_first, UnaryPred pred );
 
}}
 
}}
{{dcl | since=c++17 | num= 4 |1=
 
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryPredicate >
 
ForwardIt2 copy_if( ExecutionPolicy&& policy, ForwardIt1 first, ForwardIt1 last,
 
                  ForwardIt2 d_first,
 
                  UnaryPredicate pred );}}
 
 
{{dcl end}}
 
{{dcl end}}
  
Copies the elements in the range, defined by {{tt|[first, last)}}, to another range beginning at {{tt|d_first}}.  
+
Copies the elements in the range, defined by {{range|first|last}}, to another range beginning at {{c|d_first}} (copy destination range).
@1@ Copies all elements in the range {{tt|[first, last)}}. The behavior is undefined if {{tt|d_first}} is within the range {{tt|[first, last)}}. In this case, {{lc|std::copy_backward}} may be used instead.
+
 
@3@ Only copies the elements for which the predicate {{tt|pred}} returns {{c|true}}. The order of the elements that are not removed is preserved. The behavior is undefined if the source and the destination ranges overlap.
+
@1@ Copies all elements in the range {{range|first|last}} starting from {{c|first}} and proceeding to {{c|last}}.
@2,4@ Same as {{v|1,3}}, but executed according to {{tt|policy}}. {{cpp/enable_if| {{c|std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>}} is true}}
+
@@ If {{c|d_first}} is in {{range|first|last}}, the behavior is undefined. In this case, {{lc|std::copy_backward}} may be used instead.
 +
 
 +
@2@ Copies the elements, but executed according to {{c|policy}}.
 +
@@ {{cpp/algorithm/parallel overload precondition}}
 +
@@ If {{range|first|last}} and the copy destination range overlaps, the behavior is undefined.
 +
 
 +
@3@ Only copies the elements for which the predicate {{c|pred}} returns {{c|true}}. This copy algorithm is stable: the relative order of the elements that are copied is preserved.
 +
@@ If {{range|first|last}} and the copy destination range overlaps, the behavior is undefined.
 +
 
 +
@4@ Same as {{v|3}}, but executed according to {{c|policy}}.
 +
@@ {{cpp/algorithm/parallel overload precondition}}
 +
 
 
===Parameters===
 
===Parameters===
 
{{par begin}}
 
{{par begin}}
{{par | first, last | the range of elements to copy}}
+
{{par|first, last|the range of elements to copy}}
{{par | d_first | the beginning of the destination range.}}
+
{{par|d_first|the beginning of the destination range}}
 
{{par exec pol}}
 
{{par exec pol}}
{{par pred1 | pred | value=true | for the required elements | p1=InputIt}}
+
{{par pred1|pred|value=true|for the required elements|p1=InputIt}}
 
{{par hreq}}
 
{{par hreq}}
{{par req concept | InputIt | InputIterator}}
+
{{par req named|InputIt|InputIterator}}
{{par req concept | OutputIt | OutputIterator}}
+
{{par req named|OutputIt|OutputIterator}}
{{par req concept | ForwardIt1, ForwardIt2 | ForwardIterator}}
+
{{par req named|ForwardIt1, ForwardIt2|ForwardIterator}}
{{par req concept | UnaryPredicate | Predicate}}
+
{{par req named|UnaryPred|Predicate}}
 
{{par end}}
 
{{par end}}
  
 
===Return value===
 
===Return value===
 
 
Output iterator to the element in the destination range, one past the last element copied.
 
Output iterator to the element in the destination range, one past the last element copied.
  
 
===Complexity===
 
===Complexity===
 +
Given {{mathjax-or|\(\scriptsize N\)|N}} as {{c|std::distance(first, last)}}:
 +
@1,2@ Exactly {{mathjax-or|\(\scriptsize N\)|N}} assignments.
 +
@3,4@ Exactly {{mathjax-or|\(\scriptsize N\)|N}} applications of the predicate {{c|pred}}, and at most {{mathjax-or|\(\scriptsize N\)|N}} assignments.
  
1-2) Exactly {{tt|last - first}} assignments
+
For the overloads with an {{tt|ExecutionPolicy}}, there may be a performance cost if {{tt|ForwardIt1}}'s value type is not {{named req|MoveConstructible}}.
 
+
3-4) Exactly {{tt|last - first}} applications of the predicate
+
  
 
===Exceptions===
 
===Exceptions===
{{cpp/algorithm/parallel_exceptions_reporting_behavior|singular=no}}
+
{{cpp/algorithm/parallel exceptions reporting behavior|singular=no}}
 
+
===Notes===
+
In practice, implementations of {{tt|std::copy}} avoid multiple assignments and use bulk copy functions such as {{lc|std::memmove}} if the value type is {{concept|TriviallyCopyable}}
+
 
+
When copying overlapping ranges, {{tt|std::copy}} is appropriate when copying to the left (beginning of the destination range is outside the source range) while {{tt|std::copy_backward}} is appropriate when copying to the right (end of the destination range is outside the source range).
+
  
 
===Possible implementation===
 
===Possible implementation===
{{eq fun | 1=
+
{{eq impl
 +
|title1=copy (1)|ver1=1|1=
 
template<class InputIt, class OutputIt>
 
template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last,  
+
OutputIt copy(InputIt first, InputIt last,
 
               OutputIt d_first)
 
               OutputIt d_first)
 
{
 
{
     while (first != last) {
+
     for (; first != last; (void)++first, (void)++d_first)
         *d_first++ = *first++;
+
         *d_first = *first;
     }
+
      
 
     return d_first;
 
     return d_first;
 
}
 
}
| 2=
+
|title2=copy_if (3)|ver2=3|2=
template<class InputIt, class OutputIt, class UnaryPredicate>
+
template<class InputIt, class OutputIt, class UnaryPred>
OutputIt copy_if(InputIt first, InputIt last,  
+
OutputIt copy_if(InputIt first, InputIt last,
                 OutputIt d_first, UnaryPredicate pred)
+
                 OutputIt d_first, UnaryPred pred)
 
{
 
{
     while (first != last) {
+
     for (; first != last; ++first)
 
         if (pred(*first))
 
         if (pred(*first))
             *d_first++ = *first;
+
        {
        first++;
+
             *d_first = *first;
    }
+
            ++d_first;
 +
        }
 +
   
 
     return d_first;
 
     return d_first;
 
}
 
}
 
}}
 
}}
 +
 +
===Notes===
 +
In practice, implementations of {{tt|std::copy}} avoid multiple assignments and use bulk copy functions such as {{lc|std::memmove}} if the value type is {{named req|TriviallyCopyable}} and the iterator types satisfy {{named req|ContiguousIterator}}.
 +
 +
When copying overlapping ranges, {{tt|std::copy}} is appropriate when copying to the left (beginning of the destination range is outside the source range) while {{tt|std::copy_backward}} is appropriate when copying to the right (end of the destination range is outside the source range).
  
 
===Example===
 
===Example===
 
{{example
 
{{example
| The following code uses copy to both copy the contents of one vector to another and to display the resulting vector:  
+
|The following code uses {{tt|std::copy}} to both copy the contents of one {{lc|std::vector}} to another and to display the resulting {{lc|std::vector}}.
| code=
+
|code=
 
#include <algorithm>
 
#include <algorithm>
 
#include <iostream>
 
#include <iostream>
#include <vector>
 
 
#include <iterator>
 
#include <iterator>
 
#include <numeric>
 
#include <numeric>
 +
#include <vector>
  
 
int main()
 
int main()
Line 97: Line 117:
 
     std::vector<int> from_vector(10);
 
     std::vector<int> from_vector(10);
 
     std::iota(from_vector.begin(), from_vector.end(), 0);
 
     std::iota(from_vector.begin(), from_vector.end(), 0);
 
+
   
 
     std::vector<int> to_vector;
 
     std::vector<int> to_vector;
 
     std::copy(from_vector.begin(), from_vector.end(),
 
     std::copy(from_vector.begin(), from_vector.end(),
Line 106: Line 126:
 
// either way is equivalent to
 
// either way is equivalent to
 
//  std::vector<int> to_vector = from_vector;
 
//  std::vector<int> to_vector = from_vector;
 
+
   
 
     std::cout << "to_vector contains: ";
 
     std::cout << "to_vector contains: ";
 
+
   
 
     std::copy(to_vector.begin(), to_vector.end(),
 
     std::copy(to_vector.begin(), to_vector.end(),
 
               std::ostream_iterator<int>(std::cout, " "));
 
               std::ostream_iterator<int>(std::cout, " "));
 +
    std::cout << '\n';
 +
   
 +
    std::cout << "odd numbers in to_vector are: ";
 +
   
 +
    std::copy_if(to_vector.begin(), to_vector.end(),
 +
                std::ostream_iterator<int>(std::cout, " "),
 +
                [](int x) { return x % 2 != 0; });
 +
    std::cout << '\n';
 +
   
 +
    std::cout << "to_vector contains these multiples of 3: ";
 +
   
 +
    to_vector.clear();
 +
    std::copy_if(from_vector.begin(), from_vector.end(),
 +
                std::back_inserter(to_vector),
 +
                [](int x) { return x % 3 == 0; });
 +
   
 +
    for (const int x : to_vector)
 +
        std::cout << x << ' ';
 
     std::cout << '\n';
 
     std::cout << '\n';
 
}
 
}
| output=
+
|p=true
 +
|output=
 
to_vector contains: 0 1 2 3 4 5 6 7 8 9
 
to_vector contains: 0 1 2 3 4 5 6 7 8 9
 +
odd numbers in to_vector are: 1 3 5 7 9
 +
to_vector contains these multiples of 3: 0 3 6 9
 
}}
 
}}
 +
 +
===Defect reports===
 +
{{dr list begin}}
 +
{{dr list item|wg=lwg|dr=2039|std=C++11|before=the return value of {{tt|std::copy_if}} was not specified|after=specified}}
 +
{{dr list item|wg=lwg|dr=2044|std=C++11|before=the stability of {{tt|std::copy_if}} was not defined|after=defined}}
 +
{{dr list end}}
  
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/algorithm/dsc copy_backward}}
+
{{dsc inc|cpp/algorithm/dsc copy_backward}}
{{dsc inc | cpp/algorithm/dsc reverse_copy}}
+
{{dsc inc|cpp/algorithm/dsc reverse_copy}}
{{dsc inc | cpp/algorithm/dsc copy_n}}
+
{{dsc inc|cpp/algorithm/dsc copy_n}}
{{dsc inc | cpp/algorithm/dsc fill}}
+
{{dsc inc|cpp/algorithm/dsc fill}}
{{dsc inc | cpp/algorithm/dsc remove_copy}}
+
{{dsc inc|cpp/algorithm/dsc remove_copy}}
 
+
{{dsc inc|cpp/algorithm/ranges/dsc copy}}
 
+
 
{{dsc end}}
 
{{dsc end}}
  
[[de:cpp/algorithm/copy]]
+
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
[[es:cpp/algorithm/copy]]
+
[[fr:cpp/algorithm/copy]]
+
[[it:cpp/algorithm/copy]]
+
[[ja:cpp/algorithm/copy]]
+
[[pt:cpp/algorithm/copy]]
+
[[ru:cpp/algorithm/copy]]
+
[[zh:cpp/algorithm/copy]]
+

Latest revision as of 22:09, 25 March 2024

 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy, ranges::sort, ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
(C++11)                (C++11)(C++11)

Modifying sequence operations
Copy operations
copycopy_if
(C++11)
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17)(C++11)
(C++20)(C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
 
Defined in header <algorithm>
template< class InputIt, class OutputIt >

OutputIt copy( InputIt first, InputIt last,

               OutputIt d_first );
(1) (constexpr since C++20)
template< class ExecutionPolicy,

          class ForwardIt1, class ForwardIt2 >
ForwardIt2 copy( ExecutionPolicy&& policy,
                 ForwardIt1 first, ForwardIt1 last,

                 ForwardIt2 d_first );
(2) (since C++17)
template< class InputIt, class OutputIt, class UnaryPred >

OutputIt copy_if( InputIt first, InputIt last,

                  OutputIt d_first, UnaryPred pred );
(3) (since C++11)
(constexpr since C++20)
template< class ExecutionPolicy,

          class ForwardIt1, class ForwardIt2, class UnaryPred >
ForwardIt2 copy_if( ExecutionPolicy&& policy,
                    ForwardIt1 first, ForwardIt1 last,

                    ForwardIt2 d_first, UnaryPred pred );
(4) (since C++17)

Copies the elements in the range, defined by [firstlast), to another range beginning at d_first (copy destination range).

1) Copies all elements in the range [firstlast) starting from first and proceeding to last.
If d_first is in [firstlast), the behavior is undefined. In this case, std::copy_backward may be used instead.
2) Copies the elements, but executed according to policy.
This overload participates in overload resolution only if

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> is true.

(until C++20)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> is true.

(since C++20)
If [firstlast) and the copy destination range overlaps, the behavior is undefined.
3) Only copies the elements for which the predicate pred returns true. This copy algorithm is stable: the relative order of the elements that are copied is preserved.
If [firstlast) and the copy destination range overlaps, the behavior is undefined.
4) Same as (3), but executed according to policy.
This overload participates in overload resolution only if

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> is true.

(until C++20)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> is true.

(since C++20)

Contents

[edit] Parameters

first, last - the range of elements to copy
d_first - the beginning of the destination range
policy - the execution policy to use. See execution policy for details.
pred - unary predicate which returns ​true for the required elements.

The expression pred(v) must be convertible to bool for every argument v of type (possibly const) VT, where VT is the value type of InputIt, regardless of value category, and must not modify v. Thus, a parameter type of VT&is not allowed, nor is VT unless for VT a move is equivalent to a copy(since C++11). ​

Type requirements
-
InputIt must meet the requirements of LegacyInputIterator.
-
OutputIt must meet the requirements of LegacyOutputIterator.
-
ForwardIt1, ForwardIt2 must meet the requirements of LegacyForwardIterator.
-
UnaryPred must meet the requirements of Predicate.

[edit] Return value

Output iterator to the element in the destination range, one past the last element copied.

[edit] Complexity

Given N as std::distance(first, last):

1,2) Exactly N assignments.
3,4) Exactly N applications of the predicate pred, and at most N assignments.

For the overloads with an ExecutionPolicy, there may be a performance cost if ForwardIt1's value type is not MoveConstructible.

[edit] Exceptions

The overloads with a template parameter named ExecutionPolicy report errors as follows:

  • If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies, std::terminate is called. For any other ExecutionPolicy, the behavior is implementation-defined.
  • If the algorithm fails to allocate memory, std::bad_alloc is thrown.

[edit] Possible implementation

copy (1)
template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last,
              OutputIt d_first)
{
    for (; first != last; (void)++first, (void)++d_first)
        *d_first = *first;
 
    return d_first;
}
copy_if (3)
template<class InputIt, class OutputIt, class UnaryPred>
OutputIt copy_if(InputIt first, InputIt last,
                 OutputIt d_first, UnaryPred pred)
{
    for (; first != last; ++first)
        if (pred(*first))
        {
            *d_first = *first;
            ++d_first;
        }
 
    return d_first;
}

[edit] Notes

In practice, implementations of std::copy avoid multiple assignments and use bulk copy functions such as std::memmove if the value type is TriviallyCopyable and the iterator types satisfy LegacyContiguousIterator.

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).

[edit] Example

The following code uses std::copy to both copy the contents of one std::vector to another and to display the resulting std::vector.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
 
int main()
{
    std::vector<int> from_vector(10);
    std::iota(from_vector.begin(), from_vector.end(), 0);
 
    std::vector<int> to_vector;
    std::copy(from_vector.begin(), from_vector.end(),
              std::back_inserter(to_vector));
// or, alternatively,
//  std::vector<int> to_vector(from_vector.size());
//  std::copy(from_vector.begin(), from_vector.end(), to_vector.begin());
// either way is equivalent to
//  std::vector<int> to_vector = from_vector;
 
    std::cout << "to_vector contains: ";
 
    std::copy(to_vector.begin(), to_vector.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
 
    std::cout << "odd numbers in to_vector are: ";
 
    std::copy_if(to_vector.begin(), to_vector.end(),
                 std::ostream_iterator<int>(std::cout, " "),
                 [](int x) { return x % 2 != 0; });
    std::cout << '\n';
 
    std::cout << "to_vector contains these multiples of 3: ";
 
    to_vector.clear();
    std::copy_if(from_vector.begin(), from_vector.end(),
                 std::back_inserter(to_vector),
                 [](int x) { return x % 3 == 0; });
 
    for (const int x : to_vector)
        std::cout << x << ' ';
    std::cout << '\n';
}

Possible output:

to_vector contains: 0 1 2 3 4 5 6 7 8 9
odd numbers in to_vector are: 1 3 5 7 9
to_vector contains these multiples of 3: 0 3 6 9

[edit] Defect reports

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

DR Applied to Behavior as published Correct behavior
LWG 2039 C++11 the return value of std::copy_if was not specified specified
LWG 2044 C++11 the stability of std::copy_if was not defined defined

[edit] See also

copies a range of elements in backwards order
(function template) [edit]
creates a copy of a range that is reversed
(function template) [edit]
(C++11)
copies a number of elements to a new location
(function template) [edit]
copy-assigns the given value to every element in a range
(function template) [edit]
copies a range of elements omitting those that satisfy specific criteria
(function template) [edit]
copies a range of elements to a new location
(niebloid)[edit]