Is it valid to use std::transform with std::back_inserter?

前端 未结 4 1346
北恋
北恋 2021-02-18 13:56

Cppreference has this example code for std::transform:

std::vector ordinals;
std::transform(s.begin(), s.end(), std::back_inserter(ordinals),
         


        
4条回答
  •  情歌与酒
    2021-02-18 14:42

    From n4385:

    §25.6.4 Transform:

    template
    constexpr OutputIterator
    transform(InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperation op);
    
    template
    ForwardIterator2
    transform(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 result, UnaryOperation op);
    
    template
    constexpr OutputIterator
    transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperation binary_op);
    
    template
    ForwardIterator
    transform(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator result, BinaryOperation binary_op);
    

    §23.5.2.1.2 back_inserter

    template
    constexpr back_insert_iterator back_inserter(Container& x);
    

    Returns: back_insert_iterator(x).

    §23.5.2.1 Class template back_insert_iterator

    using iterator_category = output_iterator_tag;
    

    So std::back_inserter can't be used with parallel versions of std::transform. The versions that support output iterators read from their source with input iterators. Since input iterators can only be pre- and post-incremented (§23.3.5.2 Input iterators) and there is only sequential (i.e. non-parallel) execution, order must be preserved between them and the output iterator.

提交回复
热议问题