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

前端 未结 4 1353
北恋
北恋 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:41

    1) The output iterator requirements in the standard are completely broken. See LWG2035.

    2) If you use a purely output iterator and a purely input source range, then there's little else the algorithm can do in practice; it has no choice but to write in order. (However, a hypothetical implementation can choose to special-case its own types, like std::back_insert_iterator>; I don't see why any implementation would want to do it here, but it is permitted to do so.)

    3) Nothing in the standard guarantees that transform applies the transformations in-order. We are looking at an implementation detail.

    That std::transform requires only output iterators does not mean it cannot detect higher iterator strengths and reorder the operations in such cases. Indeed, algorithms dispatch on iterator strength all the time, and they have special handling for special iterator types (like pointers or vector iterators) all the time.

    When the standard wants to guarantee a particular order, it knows how to say it (see std::copy's "starting from first and proceeding to last").

提交回复
热议问题