是否可以使用std :: for_each来突变对象? [英] Is it ok to mutate objects with std::for_each?
本文介绍了是否可以使用std :: for_each来突变对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for_each接受InputIterators:
for_each accepts InputIterators :
//from c++ standard
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function f);
可以更改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());
此代码适用于VC ++ 2008以及GCC,代码?
(InputIterators只能保证可用作右值,在这种情况下,它们在AddOne的operator()中用作左值)
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())
推荐答案
阅读此文章。
要小心: for_each
是非修改序列操作。目的不是修改序列。但是,使用 for_each
时可以修改输入序列。
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 using for_each
.
这篇关于是否可以使用std :: for_each来突变对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文