c++ - Replace 'for loop' using std::for_each -
i have loop in below code , implement using std::for_each. have implemented it. please tell me if best way using std::for_each? if not, please suggest right one?
#include <vector> #include <cstdint> #include <string> #include <algorithm> #include <iostream> #include <sstream> int main() { std::vector<std::uint32_t> nums{3, 4, 2, 8, 15}; std::stringstream list1; (auto n : nums) { list1 << n<<","; } //is right way using std::for_each above loop can done in 1 line?? std::for_each(nums.begin(),nums.end(),[&list1](std::uint32_t n){ list1 << n << ","; }); }
yes, use of for_each
reasonable analog of preceding loop.
i feel obliged point out, however, find for_each
least useful algorithm in library. i've seen, using indicates you're still thinking in terms of loops, , changing syntax use loops. think range-based for
loops have eliminated @ least 90% of (already few) legitimate uses there used for_each
.
in case, code imitating using std::copy
std::ostream_iterator
:
std::copy(nums.begin(), nums.end(), std::ostream_iterator<std::uint32_t>(std::cout, ","));
even this, however, clumsy enough think it's open question whether it's improvement on range-based for
loop.
Comments
Post a Comment