为什么 std::for_each 是非修改序列操作?

Why is std::for_each a non-modifying sequence operation?(为什么 std::for_each 是非修改序列操作?)

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

问题描述

我刚刚在 C++ 标准中读到 std::for_each 是一个非修改序列操作,以及 findsearch 和很快.这是否意味着应用于每个元素的函数不应修改它们?这是为什么?可能会出现什么问题?

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:我知道我可以使用 std::transform 而不是 for_each,但这不是重点.

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

推荐答案

参见 这个缺陷报告他们说

LWG 认为标准中没有任何内容禁止修改序列元素的函数对象.问题是 for_each 位于名为非变异算法"的部分中,标题可能会令人困惑.非规范性说明应澄清这一点.

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.

还要注意这个.

他们似乎称之为非修改",因为 for_each 本身并没有明确修改序列的元素.

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

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

本文标题为:为什么 std::for_each 是非修改序列操作?

基础教程推荐