gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:43:18 29 4
gpt4 key购买 nike

#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();
}

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

f - function object, to be applied to the result of dereferencing every iterator in the range [first, last)

The signature of the function should be equivalent to the following:

void fun(const Type &a);

The signature does not need to have const &. The type Type must be such that an object of type InputIt can be dereferenced and then implicitly converted to Type.

所以,我的问题是:

是否有标准函数/方法来执行与 for (auto pos = x.begin(); pos != x.end();++pos) pos->Add(); 是吗?

最佳答案

不知道为什么要这样写

for_each is non-modifying

这很好用:

for_each(begin(x), end(x), [](int &i){++i;});  

对于整数的 vector,例如

关于c++ - 如何优雅地就地修改容器中的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34870071/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com