Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly modify all elements in a container in-place?

#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 seems non-modifying. 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.

So, my question is:

Is there a standard function/way to do the same as for (auto pos = x.begin(); pos != x.end(); ++pos) pos->Add(); does?

like image 407
xmllmx Avatar asked Nov 30 '22 16:11

xmllmx


1 Answers

Not sure why you write that

for_each is non-modifying

this works just fine:

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

for a vector of integers, e.g.

like image 155
Ami Tavory Avatar answered Dec 04 '22 04:12

Ami Tavory