std::transform 中的输入迭代器和输出迭代器来自同一个容器是否安全? [英] Is it safe for the input iterator and output iterator in std::transform to be from the same container?

查看:24
本文介绍了std::transform 中的输入迭代器和输出迭代器来自同一个容器是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章中,其中一个答案建议更改一个 std::string 这样的情况:

std::string str = "Hello World";std::transform(str.begin(), str.end(),str.begin(), ::toupper);

我已经使用过它,目前它在 Visual Studio 2010 中可以正常工作.但是标准是否保证它始终可以正常工作?我担心的是,我可以想象在实现中写入输出迭代器(第三个参数)可能会使输入迭代器(参数一和二)无效的可能性.

那么,综上所述,上述方法是否安全且可移植?

解决方案

是的,这保证是安全的(只要操作本身不修改元素或使迭代器无效).
来自 n3337 草案的 [alg.transform] 章节:

template输出迭代器变换(首先输入迭代器,最后输入迭代器,OutputIterator 结果,UnaryOperation op);模板输出迭代器转换(InputIterator1 first1,InputIterator1 last1,InputIterator2 first2, OutputIterator 结果,BinaryOperation binary_op);

<块引用>

2 要求:opbinary_op 不得使迭代器或子范围无效,或修改范围 [first1,last1][first2,first2 + (last1 - first1)][result,result + (last1 -first1)]代码>.

[...]

5 备注:result在一元变换的情况下可能等于first,或者在情况下等于first1或first2二进制变换.

In this post one of the answers recommends changing a std::string case this way:

std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);

I've used it and it works so far in Visual Studio 2010. But is it guaranteed by the standard to always work? My concern is that I can imagine the possibility of implementations where writing to the output iterator (the third argument) could invalidate the input iterators (arguments one and two).

So, in summary, is the above method safe and portable?

解决方案

Yes, this is guaranteed to be safe (as long as operation itself doesn't modify the elements or invalidate iterators).
From chapter [alg.transform] from draft n3337:

template<class InputIterator, class OutputIterator,  
    class UnaryOperation>  
OutputIterator  
transform(InputIterator first, InputIterator last,  
    OutputIterator result, UnaryOperation op);  

template<class InputIterator1, class InputIterator2,  
    class OutputIterator, class BinaryOperation>  
OutputIterator  
transform(InputIterator1 first1, InputIterator1 last1,  
    InputIterator2 first2, OutputIterator result,  
    BinaryOperation binary_op);  

2 Requires: op and binary_op shall not invalidate iterators or subranges, or modify elements in the ranges [first1,last1], [first2,first2 + (last1 - first1)], and [result,result + (last1 -first1)].

[...]

5 Remarks: result may be equal to first in case of unary transform, or to first1 or first2 in case of binary transform.

这篇关于std::transform 中的输入迭代器和输出迭代器来自同一个容器是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆