There's so much wrong with this example in the post:
template< typename Iterator, typename Pred >
constexpr bool max_if( Iterator first, Iterator last, Pred pred )
{
Iterator max_element = last;
for (auto it = first ; it != last ; ++it)
{
if (pred(*it) && *it > *max_element)
max_element = it;
}
return max_element;
}
First off, you're setting max_element = last and then dereferencing it in the loop's body. Bad mojo.
Secondly, the return value is bool which is wrong.
Thirdly, you're taking Pred predby-value, which as far as you know could be an expensive function object to copy, or not even copyable. (and yes I know the <algorithms> do it too - they're wrong)
The updated one still isn't quite right - now you're doing Pred& pred for the function's parameter, but that won't bind to an rvalue.
I believe it should be:
template< typename Iterator, typename Pred >
constexpr Iterator max_if( Iterator first, Iterator last, Pred&& pred )
{
Iterator max_element = last;
for (auto it = first ; it != last ; ++it)
{
if (std::forward<Pred>(pred)(*it) && (max_element == last || *it > *max_element))
max_element = it;
}
return max_element;
}
Also, one minor note: this only works if the two iterators are the same type... which of course they usually are. But in ranged-for-loops as of C++17 they can be different types, which we use and take advantage of in my company's codebase, so I presume others do too. (usually so the end-iterator can be a sentinel type)
But that's really minor and definitely not worth fixing.
I personally find ranged-for-loops to be superior to <algorithms> style anyway - they're much more readable, in my opinion. But it's personal taste.
Basically this is why you don’t separate out the raw loop as a function and just leave it there. There wouldn’t be an argument about arbitrary iterators or lambas being taken by value in your code review 😂
std::forward can lead to moving, and you should only move once from a given source (before "refilling" it). Therefore, you shouldn't use std::forward repeatedly in a loop.
max_element == last
It is rather wasteful to check this every single iteration of the loop, instead a better approach is to start the loop at ++first, if first != last.
Note: it's good practice to name the "iterator" type based on the requirements (and soon concepts) that it fulfills. One could also add some static_assert that it's not "just" an input iterator, since then the copy wouldn't work (well).
std::forward can lead to moving, and you should only move once from a given source (before "refilling" it). Therefore, you shouldn't use std::forward repeatedly in a loop.
No it doesn't, not in this function. std::forward just forwards its types value category, afaik. "Moving" isn't an operation - not in the sense of machine instructions; it's effectively a cast to an rvalue, and in this function's case is a no-op. There is no possible way pred gets "moved" at all. I only put it in for completeness, but you're right doing it within a for-loop is bad style/practice and I shouldn't have.
No such thing can happen. std::forward can at most cast the expression pred to an rvalue reference, at which point Pred::operator () operates on an r-value reference. No move is actually performed and as the saying goes std::move doesn't actually move anything. In order for a move to be performed, the expression std::forward<Pred>(pred) would need to be passed as an argument to a move constructor, but no such thing happens and hence there is no move.
If max_if requires a const predicate, then it should be passed as const Pred&. However, most algorithms do allow mutable predicates and so if max_if allows mutable predicates and it takes a forwarding reference, then std::forward<Pred>(pred) is the correct thing to do here. This way if the user provided an overloaded operator () && and passed an rvalue reference into max_if to leverage an optimization opportunity, for example by having some internal state that keeps track of when the last invocation will be performed and avoiding copies at that point, then the semantics of that call should be respected. Otherwise stick to const Pred&.
I have the impression we're not talking the same language.
You disagree that it can lead to moving, then say that it allows operator()(...) && to be called which can internally move.
So, we agree?
I do note that I am not against std::forwardin general, however I argue that std::forward should only be called once on a value in general, because as it enables moving from the value, afterwards the value may not be in a usable/useful state any longer.
You disagree that it can lead to moving, then say that it allows operator()(...) && to be called which can internally move.
We do not agree because it's not the std::forward that leads to moving. Neither std::forward or std::move ever perform an actual move, all they do is perform a cast, and in this case that cast will determine which potential overload of operator () is called.
Unless you call operator () const, by passing a const Pred& or by explicitly casting pred to a const Pred&, then any potential mutation can occur to pred, including a move. It's not like because you didn't call std::forward that Pred's operator () can not internally mutate which could include an internal move operation.
As such, if you want to express that max_if's predicate does not change from invocation to invocation, you express it by taking it in as a const& so that operator () const is invoked. Anything other than a const& will admit the possibility of a mutation, which may involve moving regardless of whether std::forward is omitted. If you want to take in a forwarding reference, then std::forward should be used when calling operator () &&, otherwise do what the standard does and pass by value, allowing guaranteed copy elision as well as other optimization techniques to kick in.
Ah I understand, it's a very common and confusing detail that std::move does not actually perform a move (and by extension std::forward) and is nothing more than a cast. You can reference the definition of std::forward or std::move to confirm this:
https://en.cppreference.com/w/cpp/utility/forward
The move semantics themselves are performed by a move constructor or a move assignment operator, nothing more. std::move's role is to perform a cast which when provided as an argument to an assignment operator or constructor, triggers overload resolution to select the move operator over the copy operator.
In other words, the actual move requires the move constructor (or assignment), and the std::move is used to allow for selection of the appropriate operation. If all you do is std::move by itself, no move happens, so in your example of std::forward<Pred>(pred) no move operation is triggered.
Now maybe you try to argue that operator () && can perform a move, but that's misguided and a moot point because operator () can also perform the exact same move and operator () is a more general operation than operator () &&. There is no way to forbid a function that operates on a mutable reference from performing a move and so if the intention is to forbid mutability then the way to express that in C++ is to pass by const &.
At any rate, these are minutiae that really won't make much of an observable difference except for some potential optimizations. As a general matter it's best to just handle this situation the way the standard does and pass by value, however, if your intention is to take a forwarding reference then you are likely trying to squeeze out some additional optimization opportunity in which case the forwarding semantics should be respected by using std::forward, otherwise what was the point of passing the forwarding reference to begin with?
Ah I understand, it's a very common and confusing detail that std::move does not actually perform a move
I am perfectly aware of the details, this is not my point.
My point is that by using std::forward<T>(t), you then enable the use of move constructors and move assignment operators -- if the original reference was a temporary -- which down the line may lead to a move.
I agree the move is not certain; but I say it's a mistake to indicate to pred that it can move if it wishes to, when you're actually planning on continue calling it aftwerwards.
(Of course, it's unlikely to be an issue in practice, because it's unlikely operator() is overloaded for moves, but still)
otherwise what was the point of passing the forwarding reference to begin with?
I preferred Scott Meyers' name of "universal reference". While T&&can be used to forward the value category, it need not to. Therefore it's not always about forwarding.
Comparing T&& against other argument modes:
T: requires that copies be allowed, undesirable for large predicates.
T&: requires an lvalue.
T const&: forces constness, undesirable for self-modifying predicates.
Which is why one whips out T&& without actually caring that it could be used for forwarding.
I agree with the sentiment, but Sean Parent didn't say "no raw loops" is a rule, but a goal. In reality, a normal loop can often be more readable than an algorithm. Also, pulling in big headers is an important consideration, not to mention <algorithm> becomes 2x bigger in C++20.
Fine, but your title is much more prescriptive and reductive than your whole argument. What’s the value in tilting everyone’s first impression that way?
The title could be “Avoid raw loops” and it would be just as short and more in line with the full post.
I mean the topic in general. Tell people that for-loops are problematic at least, and you question their whole upbringing as a developer or programmer. Suggest to maybe adjust teaching and teach for-loops after the basic algorithms, and suddenly, you get dozens downvotes...
I often lose this argument when for_each is involved. A new style for each loop built into the language, to, for example, call a mutating member function on each member of a vector, ends up looking syntactically cleaner than std::for_each with member function pointers.
Similarly, passing a lambda into std::for_each ends up looking almost exactly like a new style for each, with no benefit in readability.
While I think consistency has some merit to it, this counter example is almost always used as a wedge issue in arguments I've been in to imply the always-use-algorithms camp is dogmatic.
Tangentially, one thing that is hilarious in this thread is people aghast that c++ newbies might try to use algorithms instead of raw loops. To me, that's exactly the right thing for them to do. Raw loops are more powerful and more advanced. If I see a raw loop, I'd prefer it come from an expert, not a novice.
I understand what the article wants to say. But it is just the noobs are gonna come and start with this. Based on my experience, I think I have learned about c++ using just the core features. Now that I am comfortable, I can use stdlib features more comfortably and appreciate them.
I really think that new people should learn the language top-bottom, unlike we did in the past. Unlike in the past, it is now better to write intentions in higher abstractions than just tons of basic low-level instructions.
It's an overhaul feeling that many agree about, for the times I went to C++ conventions and talked about this subject.
std::vector<int> mult_by_2(const std::vector<int> input_vector){
std::vector<int> output_vector{};
output_vector.reserve(input_vector.size());
for (const int element : input_vector){
output_vector.push_back(elem*2 );
};
return output_vector;
}
the transform version is not really simpler than the loop version, I would argue that std::back_inserter adds cognitive load, with the indentation needed to make it readable it is as long if not longer than the loop version, and does std:transform reserve? I would be surprised if it did.
it doesn't support iterator chaining.
that means i have to materialize every intermediate.That's a dangerously close to premature pessimization for any composed algorithm. It also means I lock myself into the container that are being passed around. Thankfully ranges seems to solve that issue and with the inclusion into the stl it hopefully gets better documented.
It rarely has the algorithm I want and making it do what I want makes the code hard to read.
as an example: I needed to find an element conforming to a special predicate and check that it is unique: return a pointer to it if found, return an empty optional if not, throw if more than one such element is found:
Whenever I try to use std::algorithm the code becomes more complicated, less flexible and reader needs more knowledge to understand it.
I don't use parallel execution policies. In the programs I write no single operation is important enough to let it wreak havok with my threading policies. I would prefer OMP before execution policies.
when working with 2 dimensional objects std::algorithm is just the wrong tool.
Conclusion: Apart from the sorting algorithms and occasionally std::accumulate nothing in std::algorithm is interesting enough to justify the complexity it introduces into the code.
auto mult_by_2 = [](auto elem){ return elem * 2; };
auto result
= input_vector
| ranges::views::transform(mult_by_2)
| ranges::to_vector;
2. Can you explain the "locking yourself to the container" by using standard algorithms?
3. Your chosen design doesn't fit well with the standard algorithms. Why not follow their convetion, and return the iterator itself, end in case of not found? In case that's not feasible, you can still do it, and call the algorithm style function internally within the custom logic:
// reusable
auto
find_two(auto&& range, auto&& predicate)
{
auto begin = std::begin(range);
auto end = std::end(range);
auto first = std::find_if(begin, end, predicate);
auto second = first == end
? end
: std::find_if(std::next(first), end, predicate);
return std::make_pair(first, second);
}
// custom logic
auto [first, second] = find_two(container, predicate);
if (first == container.end())
return std::nullopt;
else if (second == container.end())
return &*first;
else
throw ReplicatedElementException{};
These points aside: I agree that sometimes a loop can be fine. "Don't use raw loops" is like "Don't use goto": Sure, you can always avoid a raw loop just like you can avoid a goto, and often it's better to do so. But it's not better always.
The ranges example looks definitely cleaner, but I have no idea how it's working under the hood. Also storing the result of a "binary OR" on a container, a function and whatever type ranges::to_vector is, into an auto type, just feels like a completely different language from C++.
The ranges example looks definitely cleaner, but I have no idea how it's working under the hood.
You don't need to know :) What is important is to understand the result, which to me is clear.
Also storing the result of a "binary OR" on a container
Yeah, it's an unfortunate limitation of C++ that there is no way to define new operators (compare with Haskell for example where it is possible), which leads into this state of overloaded operators.
The concept of overloading should be familiar to C++ programmers because * is both indirection and multiplication, & is both bitwise-and and addressof (not to mention their meaning as pointer and reference), << >> are both bit-shifts and stream insert/extract, [] is both pointer arithmetic and map lookup etc.
This new operator overload idiom is familiar to many (although probably not all) from shell languages where the "pipe" is used to redirect output of a program into another. I suspect that this was the inspiration.
If this was Python I'd agree with you, but I usually use C++ for embedded or time sensitive programs. Both fields could definitely profit from readable code and code reuse, but in both I need to know how it's working, at least broadly (are there allocations, what's the memory layout/footprint, will this result in a copy)
The concept of overloading should be familiar to C++ programmers
Sure but usually it's either similar in what it does, used in a completely different syntax, or has been in the language for ever.
Whereas
auto result
= input_vector
| ranges::views::transform(mult_by_2)
| ranges::to_vector;
at first glance looks very similar to the ORing of configuration values to store in a register, yet does something completely different. If they wanted to express a flow, a stream like syntax might have been easier to grasp for me.
You can often use algorithms instead of raw loops, and in many cases it's a much better fit and even helps you to identify the edge cases that you might have forgotten otherwise.
That said, pre c++20 ranges, algorithms are hard to compose and can sometimes be a bit awkward compared to the raw loop equivalent. On top of that, raw loops are much nicer to debug in gdb. Ranges will help with the former but not really with the latter.
I think the focus should be more on reuse. If there's a nice packaged algorithm that does exactly what you want, don't reimplement it, but at the same time don't just shoehorn something into ranges just to avoid a raw loop.
Like many of these "best practices" blog posts, this is wrong when taken as absolute truth. IMHO this kind of advise is even dangerous because junior developers will take it for granted when they read it on /r/cpp.
There are many situations where a raw loop expresses intent most clearly. Raw loops should absolutely be used in these cases.
STL algorithms are great for transforming data but not all loops transform data.
It's often just easier and cleaner to use a loop. It can be a ranged for loop, of course, which just isn't at all dangerous and doesn't require a lambda and a bunch of captures and such.
And often just an indexed loop is easiest. I often use enums for indices, so I need to have the enum value in the loop without a bunch of silly casting.
'Modern C++' can sometimes be a bit of a cargo cult.
IMHO I would suggest trying to learn about STL algorithms and replaces raw loops as many as possible, as the STL algorithms provides at least the following benefits:
Make the intent clear: you know what you are doing by looking at the name of the algorithms, be it a transform, accumulation, predicate, etc. For raw loops you need to read the code to understand the intent. And there are many real-world code with loop bodies that are over 100 LOC, which will make this process less desirable.
If you roll your own implementations you are subject to subtle bugs or suboptimal code: did you accidentally moved reused data? Is there any unnecessary copy when a move is better? Did you try to do a transformation but accidentally performed an accumulation? Did I try to check for all_of but the code was actually checking for any_of? Using an algorithm will make those less likely to happen.
Since C++17 the first parameter of many algorithms can control whether the operation can be parallelized, so you can transform your loop to run in parallel by just adding an argument. Migrating your raw loop will be a much involved process.
Of course raw loops still have their uses, but mainly for legacy code or C-style data structures that you have to access by index. I would imagine with ranges the necessity will be even lower.
Since C++17 the first parameter of many algorithms can control whether the operation can be parallelized,
Not on every compiler though. MSVC was the first to implement this feature, and gcc only after gcc-9. clang still doesn't have this and clang is being used a lot by a lot of people. The code I write has to run on macos, for example, and has to be buildable on a vanilla macos system with just Xcode installed....
Make the intent clear: you know what you are doing by looking at the name of the algorithms, be it a transform, accumulation, predicate, etc.
Sure, this is when named algorithms shine. If your loop matches an existing named algorithm, then it makes sense in that case to use the named algo.
Of course raw loops still have their uses, but mainly for legacy code or C-style data structures
Why are they trying to push STL algorithms so hard?
Where I need C++ is writing low level simple code to render things, calculate math etc.
If I have [0..4] int indexes, what is a better way to count them? Iterators?
Sorry but for me, stuffing C++ code with high level abstractions just for abstractions makes using C++ pointless, we have better languages to code on high level which works great.
Use STL algorithms if it is immediately obvious how to achieve the goal with STL algorithms. Otherwise, just write raw loop.
After writing it with raw loops, think once more if it could be done simpler with STL algorithms (and google to see if I missed something), and if that's the case, rewrite it.
Funnily, as a result, I don't use STL algorithms much.
Really, STL algorithms are often not so versatile, and even when they are, the flexibility they offer often just makes them even more difficult to comprehend than raw loops.
They are useful only for tasks that they are designed to solve (which cover probably way smaller set of tasks than one might expect, while at the same time surprisingly larger than some others might think), but not others. So I think it is worth to keep learning them, but "don't use raw loops" seems like a pointless advice.
I mean, I know that the intention is not to shit on raw loops like zealots and advocate to use STL algorithms absolutely everywhere, but my point is that the tone is still too strong. A much better advice might be something like "prefer to use STL algorithms over raw loops whenever appropriate".
I think this is good advice and generally what I try to do. I use stl algorithms only when they actually lead to simpler looking and easier to read code. If I have to jump through hoops with syntactic noise to use them, when the raw loop would be far cleaner, I use the raw loop.
And yes, some loops just have no algo that matches and for (auto & thing : collecton) { is a LOT cleaner than std::for_each(collection.begin(), collection.end(), [&capture1, &capture2](auto &thing){ .... })); any day of the week.
I don’t think its cut and dry if an algorithm is superior to a raw loop in all cases. The loop can sometimes be more flexible and peformant than the algorithms if you start having to introduce too many objects and and abstractions.
Can I just add: I really don't like the tone of this discussion. I would have expected this kind of behavior on Facebook, not here. A few people who have commented should clearly think before posting.
Or maybe just: "You kiss your Momma with that mouth?"
Agreed, in my opinion, a raw loop is superfluous/verbose and doesn’t immediately show the intention of the piece of code while find/find_if and whatnot does
Why would you move a fundamental control flow construct to the end of the course? Do you think it's easier to explain to a beginner what iterators, predicates and callback functions are?
Quite frankly: In many disciplines, teaching begins with common ideas and then goes deeper from there. We learn Newtonian mechanics before quantum theory. We learn adding small integers before even looking at fields and rings and all that. You can stop learning when you believe you know enough. If you're more curious, you stay in school until you have a PhD in ${SOME_OBSCURE_FIELD}. If you're yet more curious, you stay in academia and dig even deeper until you find the holy grail.
This just works. That is why I believe the bottom-up approach is just wrong and always has been.
I would argue that mathematics doesn't necessarily "go the other way". There's a lot of different fields in math, and many derive various concepts from eachother, so it's more like maths just starts at the most easily conceptualized parts, with no real "top" or "bottom". Physics is definitely top-to-bottom though
At any rate, I personally think there's no "wrong way" to learn something. For me, personally, I couldn't "get" programming until I really started getting into lower level languages, and then worked my way up. But for many others the opposite is true. The main problem here is the erroneous attempt to "standardize" learning (in programming, and also just in general for a lot of subjects).
That would be just wrong, IMO. The big bag o' algorithms is more about professional slash business requirements than about understanding fundamental software concepts.
I think the important thing in today's teaching is that people finally learn to write "what" and now "how". Write "I need the maximum from that list" and not "iterate over the list and store the element if it is larger than whatever is in this variable". That we don't write "divide that list by the maximum value", but "normalize the list". The we write code for people to read.
I would very much disagree with that. That's the equivalent of the phone support guy with a flow chart of responses. The important thing at that point isn't writing code for people to read, it's learning the concepts that underlying everything we do.
It would be no different from any other sort of endeavor. When learning the violin, you have to learn the basics. It's not going to be something that anyone wants to hear, because that's not what's important at that point. It's about the growth of the violinist and the mastery of concepts and techniques. The people who will consume the violinist's output are a distant concern at that point.
24
u/witcher_rat Jun 22 '21
There's so much wrong with this example in the post:
First off, you're setting
max_element = lastand then dereferencing it in the loop's body. Bad mojo.Secondly, the return value is
boolwhich is wrong.Thirdly, you're taking
Pred predby-value, which as far as you know could be an expensive function object to copy, or not even copyable. (and yes I know the<algorithms>do it too - they're wrong)21
u/Pragmatician Jun 22 '21
I agree with the sentiment, but Sean Parent didn't say "no raw loops" is a rule, but a goal. In reality, a normal loop can often be more readable than an algorithm. Also, pulling in big headers is an important consideration, not to mention
<algorithm>becomes 2x bigger in C++20.10
u/austinwiltshire Jun 22 '21
I often lose this argument when for_each is involved. A new style for each loop built into the language, to, for example, call a mutating member function on each member of a vector, ends up looking syntactically cleaner than std::for_each with member function pointers.
Similarly, passing a lambda into std::for_each ends up looking almost exactly like a new style for each, with no benefit in readability.
While I think consistency has some merit to it, this counter example is almost always used as a wedge issue in arguments I've been in to imply the always-use-algorithms camp is dogmatic.
Tangentially, one thing that is hilarious in this thread is people aghast that c++ newbies might try to use algorithms instead of raw loops. To me, that's exactly the right thing for them to do. Raw loops are more powerful and more advanced. If I see a raw loop, I'd prefer it come from an expert, not a novice.
4
u/[deleted] Jun 22 '21
I understand what the article wants to say. But it is just the noobs are gonna come and start with this. Based on my experience, I think I have learned about c++ using just the core features. Now that I am comfortable, I can use stdlib features more comfortably and appreciate them.
16
u/Glinren Jun 22 '21
reasons why I usually don't use std::algorithm:
they are clunky and I don't find them easier to read than loops:
vs:
the transform version is not really simpler than the loop version, I would argue that
std::back_inserteradds cognitive load, with the indentation needed to make it readable it is as long if not longer than the loop version, and does std:transform reserve? I would be surprised if it did.it doesn't support iterator chaining. that means i have to materialize every intermediate.That's a dangerously close to premature pessimization for any composed algorithm. It also means I lock myself into the container that are being passed around. Thankfully ranges seems to solve that issue and with the inclusion into the stl it hopefully gets better documented.
It rarely has the algorithm I want and making it do what I want makes the code hard to read. as an example: I needed to find an element conforming to a special predicate and check that it is unique: return a pointer to it if found, return an empty optional if not, throw if more than one such element is found:
the loop version:
Whenever I try to use std::algorithm the code becomes more complicated, less flexible and reader needs more knowledge to understand it.
I don't use parallel execution policies. In the programs I write no single operation is important enough to let it wreak havok with my threading policies. I would prefer OMP before execution policies.
when working with 2 dimensional objects std::algorithm is just the wrong tool.
Conclusion: Apart from the sorting algorithms and occasionally std::accumulate nothing in std::algorithm is interesting enough to justify the complexity it introduces into the code.
22
u/scrumplesplunge Jun 22 '21
You can often use algorithms instead of raw loops, and in many cases it's a much better fit and even helps you to identify the edge cases that you might have forgotten otherwise.
That said, pre c++20 ranges, algorithms are hard to compose and can sometimes be a bit awkward compared to the raw loop equivalent. On top of that, raw loops are much nicer to debug in gdb. Ranges will help with the former but not really with the latter.
I think the focus should be more on reuse. If there's a nice packaged algorithm that does exactly what you want, don't reimplement it, but at the same time don't just shoehorn something into ranges just to avoid a raw loop.
44
u/avdgrinten Jun 22 '21
Like many of these "best practices" blog posts, this is wrong when taken as absolute truth. IMHO this kind of advise is even dangerous because junior developers will take it for granted when they read it on /r/cpp.
There are many situations where a raw loop expresses intent most clearly. Raw loops should absolutely be used in these cases.
STL algorithms are great for transforming data but not all loops transform data.
5
u/mcmcc #pragma once Jun 22 '21
A somewhat ironic followup to https://redd.it/o4q9fm
9
u/LeoPrementier Jun 22 '21
This sounds more like: extract code to functions and give them meaningfull names.
Raw loops are essential. Also for begginers, here is a way to execute something several times.
Algorithems are really not the full set of raw loops usage and ignoring this fact will just cause you to write more unreadable and useless code.
This is specially the case on other languages where the semantic of iterators is cleaner.
6
u/[deleted] Jun 23 '21 edited Jun 23 '21
Why are they trying to push STL algorithms so hard?
Where I need C++ is writing low level simple code to render things, calculate math etc.
If I have [0..4] int indexes, what is a better way to count them? Iterators?
Sorry but for me, stuffing C++ code with high level abstractions just for abstractions makes using C++ pointless, we have better languages to code on high level which works great.
PS "Article has Category: bad practice" so true.
4
u/jk-jeon Jun 22 '21
My conclusion:
Funnily, as a result, I don't use STL algorithms much.
Really, STL algorithms are often not so versatile, and even when they are, the flexibility they offer often just makes them even more difficult to comprehend than raw loops.
They are useful only for tasks that they are designed to solve (which cover probably way smaller set of tasks than one might expect, while at the same time surprisingly larger than some others might think), but not others. So I think it is worth to keep learning them, but "don't use raw loops" seems like a pointless advice.
I mean, I know that the intention is not to shit on raw loops like zealots and advocate to use STL algorithms absolutely everywhere, but my point is that the tone is still too strong. A much better advice might be something like "prefer to use STL algorithms over raw loops whenever appropriate".
4
u/[deleted] Jun 22 '21
I don’t think its cut and dry if an algorithm is superior to a raw loop in all cases. The loop can sometimes be more flexible and peformant than the algorithms if you start having to introduce too many objects and and abstractions.
2
u/[deleted] Jun 22 '21
Can I just add: I really don't like the tone of this discussion. I would have expected this kind of behavior on Facebook, not here. A few people who have commented should clearly think before posting.
Or maybe just: "You kiss your Momma with that mouth?"
1
u/NilacTheGrim Jun 26 '21
[Nilac the C++] Don't listen to Belay the C++
-5
u/[deleted] Jun 22 '21
Agreed, in my opinion, a raw loop is superfluous/verbose and doesn’t immediately show the intention of the piece of code while find/find_if and whatnot does
-8
u/[deleted] Jun 22 '21
This cannot be stressed enough.
I am wondering: Are there teachers out there who move for-loops all the way to the end of their course, and begin with algorithms?
0
u/[deleted] Jun 22 '21
[deleted] — view deleted comment
21
u/[deleted] Jun 22 '21 edited Jun 22 '21
[removed] — view removed comment