Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

idiomatic way of changing container elements while iterating over the container

Is the following way of manipulating a string or a container idiomatic?

string s = "hello";
for (auto &p : s) {
    p = somefunction(p); // somefunction without side effects
}

This implies iterating over a range while changing the contained elements. The container is not modified in its layout so the iterators should be valid during the iteration.

The same effect could of course easily "be coded" differently, but I am interested in if this is the idiomatic way of doing it?

I asked a similar question earlier, but that was related to the case where the container's layout is being modified, and here the answer is: iterate over a copy of the container. C++ idiomatic way of iterating over a container that itself is being modified

like image 503
mrchance Avatar asked Oct 15 '25 04:10

mrchance


1 Answers

Idioms can change over time, so here's a C++20 version that might very well become idiomatic in the not too distant future.

std::ranges::transform(s, s.begin(), someFunction);

Here's a demo.

like image 126
cigien Avatar answered Oct 16 '25 17:10

cigien