如何优雅地修改容器中的所有元素?

xml*_*lmx 3 c++ algorithm containers stl c++11

#include <vector>

using namespace std;

class A
{
public:
    A() = default;

    void Add()
    {
        a++;
    }

private:
    int a;
};

int main()
{
    vector<A> x(10);
    for (auto pos = x.begin(); pos != x.end(); ++pos) pos->Add();
}
Run Code Online (Sandbox Code Playgroud)

for_each似乎没有修改.http://en.cppreference.com/w/cpp/algorithm/for_each

f - 函数对象,应用于取消引用范围[first,last]中每个迭代器的结果

函数的签名应该等同于以下内容:

void fun(const Type&a);

签名不需要const&.类型Type必须是可以取消引用InputIt类型的对象,然后隐式转换为Type.

所以,我的问题是:

是否有标准的功能/方式来做同样的事情for (auto pos = x.begin(); pos != x.end(); ++pos) pos->Add();

Ami*_*ory 9

不知道你为什么这么写

for_each是不修改的

这很好用:

for_each(begin(x), end(x), [](int &i){++i;});  
Run Code Online (Sandbox Code Playgroud)

对于vector整数,例如


650*_*502 5

你可以用

for(auto& p : x) p.Add();
Run Code Online (Sandbox Code Playgroud)

该代码简单,优雅,但也非常有效,因为它允许编译器直接看到操作而无需插入额外的逻辑。打字时打字少,打字速度快,没​​有胡扯的胡言乱语。

例如,由g ++生成的代码

for (auto& y : x) {
    y++;
}
Run Code Online (Sandbox Code Playgroud)

其中x被声明为的std::vector<int>具有一个内部循环,例如

.L8:
    movdqa  (%rdi,%rax), %xmm0
    addq    $1, %rdx
    paddd   %xmm1, %xmm0
    movaps  %xmm0, (%rdi,%rax)
    addq    $16, %rax
    cmpq    %rdx, %r8
    ja  .L8
Run Code Online (Sandbox Code Playgroud)

其中使用mmx指令在每次迭代中递增4个整数。