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

2021-12-26 00:00:00 standards foreach c++ stl

我刚刚在 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.

相关文章