の最初の可能な実装を調べるとstd::transform
template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op)
{
while (first1 != last1) {
*d_first++ = unary_op(*first1++);
}
return d_first;
}
「安全」ではないように見えるかもしれません。
ただし、std::transform(str.begin(), str.end(),str.begin(), ::toupper);
d_first
とfirst1
同じ場所を指していますが、それらは同じイテレータではありません!
1 つのステートメントで両方のイテレータをインクリメントしても問題はありません。
別の実装は、(MingW ヘッダー ファイルから) このようなもので、同等ですが、少しきれいに見えます。
template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op)
{
for (; first1 != last1; ++first1, ++d_first)
*d_first = unary_op(*first1);
return d_first;
}
John Bartholomew のおかげで編集