How would I rewrite the code below for example, using an STL algorithm without a loop?
vector<double> pizzaBox;
int biggestSlice = 0;
for (int* p = &pizzaBox[0]; p != pizzaBox[pizzaBox.size()]; p++) {
if(*p > biggestSlice)
biggestSlice = *p;
}
Assuming that you actually meant vector<int>
, and after correcting your loop end condition, you can use the max_element
algorithm here:
int biggestSlice = *max_element(pizzaBox.begin(), pizzaBox.end());
(Notice that max_element
returns an iterator, hence I’m dereferencing the return value before assigning to biggestSlice
.)
This of course no longer works (= yields undefined behaviour) when the vector is empty. You need to test for this explicitly before dereferencing the return value of the function.
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