Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of loop using pointers rewritten using an STL algorithm, without a loop?

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;
}
like image 324
Bernie Avatar asked May 12 '11 12:05

Bernie


1 Answers

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.

like image 110
Konrad Rudolph Avatar answered Oct 21 '22 08:10

Konrad Rudolph