使用 std::for_each 改变对象可以吗?
for_each 接受 InputIterators :
//from c++ standard
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function f);
是否可以更改 Function f 中的对象,如下所示:
struct AddOne
{
void operator()(int & x){x = x + 1;}
};
std::vector<int> vec(10);
std::for_each(vec.begin(),vec.end(),AddOne());
此代码适用于 VC++2008 以及 GCC,但它也是可移植(合法)代码吗?
(InputIterators 仅保证可用作右值,在这种情况下,它们在 AddOne 的 operator() 中用作左值)
for_each accepts InputIterators :
//from c++ standard
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function f);
is it ok to change the object in Function f, like this :
struct AddOne
{
void operator()(int & x){x = x + 1;}
};
std::vector<int> vec(10);
std::for_each(vec.begin(),vec.end(),AddOne());
This code works in VC++2008 and also with GCC, but is it also portable (legal) code ?
(InputIterators are only guaranteed to be usable as rvalue, in this case they are used as lvalue in AddOne's operator())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
阅读这篇文章。
迂腐一点:
for_each
是一个非修改序列操作。 目的不是修改顺序。 不过,使用for_each
时可以修改输入序列。Read this article.
To be pedantic:
for_each
is a non-modifying sequence operation. The intent is not to modify the sequence. However, it is okay to modify the input sequence when usingfor_each
.你误解了一些东西。 说输入迭代器仅保证可用作右值并不意味着您无法以某种方式从迭代器中获取左值。 所以这并不意味着
*iterator
的结果是右值。 你/for_each 传递给AddOne
的是operator*
的结果 - 不是迭代器本身。关于
for_each
和修改函数对象 - 阅读You misunderstand something. Saying input iterators are only guaranteed to be usable as rvalues doesn't mean you can't get an lvalue out of an iterator somehow. So it does not mean that the result of
*iterator
is an rvalue. What you/for_each passes toAddOne
is the result ofoperator*
- not the iterator itself.About
for_each
and a modifying function object - read this question如果有疑问,请使用 std::transform,因为它甚至会向代码的临时读者传达您打算修改某些内容。
If in doubt use std::transform as it will convey even to the casual reader of your code that you intend to modify something.
这是合法的 - 输入迭代器用于指定范围,而不是进行处理。
有趣的是,Josuttis 在他的《C++ 标准库》一书中将
for_each
列为修改性,而不是非修改性。It is legal - the input iterators are used to specify the range, not to do the processing.
Interestingly, Josuttis in his book "The C++ Standard Library" lists
for_each
as modifying, raher than non-modifying.我的建议是,如何将项目传递给函数(即通过引用或指针并更改它或作为副本并更改它)非常重要。
但正如其他人所说,如果您想更改值,最好使用转换,因为它关心返回值。
My suggestion would be, it all matters how you pass your item to the function i.e. whether by reference or pointer and change it or as a copy and change it.
But as other's have said, if you want to change the values, it's better to use transform as it cares about the return values.