为什么std :: for_each是一个非修改序列操作? [英] Why is std::for_each a non-modifying sequence operation?

查看:111
本文介绍了为什么std :: for_each是一个非修改序列操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在C ++标准中看到 std :: for_each 是一个非修改序列操作,以及 find search 等。这是否意味着应用于每个元素的函数不应该修改它们?这是为什么?什么可能会出错?



这是一个示例代码,其中序列被修改。你能看到什么错误吗?

  void foo(int& i)
{
i = 12;
}

int main()
{
std :: vector< int> v;
v.push_back(0);

std :: for_each(v.begin(),v.end(),foo);
// v现在包含12
}

我怀疑这只是一个解释问题,但我想要你的意见。



PS:我知道我可以使用 std :: transform

而不是 for_each >请参阅他们说的此缺陷报告


LWG认为标准中没有任何内容禁止修改序列元素的函数对象。问题是for_each在一个名为nonmutating算法的部分,标题可能是混乱。


但是请注意这一个



他们似乎将其称为非修改,因为for_each本身不会激活修改序列的元素。


I just read in the C++ standard that std::for_each is a non-modifying sequence operation, along with find, search and so on. Does that mean that the function applied to each element should not modify them? Why is that? What could possibly go wrong?

Here is a sample code, where the sequence is modified. Can you see anything wrong with it?

void foo(int & i)
{
    i = 12;
}

int main()
{
    std::vector<int> v;
    v.push_back(0);

    std::for_each(v.begin(), v.end(), foo);
    // v now contains 12
}

I suspect this to be just an interpretation issue, but I wanted to have your opinion about that.

PS: I know I could use std::transform instead of for_each, but that's not the point.

解决方案

See this defect report they say

The LWG believes that nothing in the standard prohibits function objects that modify the sequence elements. The problem is that for_each is in a secion entitled "nonmutating algorithms", and the title may be confusing. A nonnormative note should clarify that.

But also note this one.

They seem to call it "non-modifying" because for_each itself does not exlicitly modify the elements of the sequence.

这篇关于为什么std :: for_each是一个非修改序列操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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