4 ms·
>1. This sort of for loop is idiomatic C++ code. No. This is C code. In C++ you write: std::vector<int> a = { 1, 2, 3 }; std::cout << std::min_element
by shin_lao 12y ago
>1. This sort of for loop is idiomatic C++ code.
No. This is C code. In C++ you write:
std::vector<int> a = { 1, 2, 3 };
std::cout << std::min_element(a.cbegin(), a.cend()) << std::endl;
You shouldn't be writing a lot of loops in C++. You should be using the algorithms as much as possible.
- humanrebar 12y agoI'm aware of algorithms and espouse them, but you're not comparing apples to apples. The example is about mutating a collection while iterating over it: for(std::vector<int>::const_iterator it=v.begin(); it!=v.end(); ++it) { if (*it < 5) v.push_back(5-*it); } ...you could do that with std::for_each and a lambda, or maybe some creative use of std::back_inserter, but you'd still have iterator invalidation problems. The right way to do it might be to use a while loop that uses std::find_if to find the next value to insert, but I'm not sure how you'd arrive at that solution without thinking about iterator invalidation in the first place. ...and the point is that Rust effectively says "you can't iterate over a mutable collection like that" while a less battle-scarred C++ developer might not even notice the problem before deploying to production.
- louiz 12y agoActually the simplest way to dix that code ils to write it = v.push_back(5-*it);
- jjnoakes 12y agoDon't use "std::endl" unless you intend to flush the stream (doubtful in this case). It's not a replacement or synonym for "\n".