ebvtrnog
ebvtrnog

Reputation: 4367

C++ transform and lambda

Is it possible to turn this into simple and nice usage of std::transform?

int j = 0;
for (auto &vi : V)
{
    auto div_res = div(vi + j, 10);
    j = div_res.quot;
    vi = div_res.rem;
}

This code does a very simple thing and it feels that is should be much shorter and clearer.

Or, if not transform, is there any std function that makes this sort of things easier?

Upvotes: 1

Views: 802

Answers (1)

vsoftco
vsoftco

Reputation: 56547

What about:

std::transform(vi.begin(), vi.end(), vi.begin(), 
    [&j](auto elem) /* or const auto& elem */
    {
        auto div_res = div(elem + j, 10);
        j = div_res.quot;
        return div_res.rem;
    }
);

However in this case a range-based for is probably as good (if not better) than std::transform.

Upvotes: 3

Related Questions