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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With