Why is std::for_each a non-modifying sequence operation?(为什么 std::for_each 是非修改序列操作?)
问题描述
我刚刚在 C++ 标准中读到 std::for_each
是一个非修改序列操作,以及 find
、search
和很快.这是否意味着应用于每个元素的函数不应修改它们?这是为什么?可能会出现什么问题?
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 是非修改序列操作?
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01