Algorithms STL Mcq- What is the correct answer?

Q8. Algorithms STL#8
Study the following code snippet:

vector< int > data = {100, 142, 138, 96, 32, 149};
swap(data[2], data[5]);
int val1 = *max_element(data.begin(), data.begin() +3);
int val2 = *max_element(data.begin()+3,data.end());
cout<< min(val1, val2);
Will the above code compile? If yes then what is the output?

swap is not a defined function so an error is thrown.

output is 142, no error is thrown.

max_element is not a defined function so an error is thrown.

output is 138, no error is thrown.

Why is the answer d and not c

after swapping the vector becomes
100 142 149 96 32 138

int val1 = *max_element(data.begin(), data.begin() +3);

val1 will be 149

int val2 = *max_element(data.begin()+3,data.end());
val2 will be 138

so min(149,138) will be 138
hence ans is d

NOTE
max_element
Returns an iterator pointing to the element with the largest value in the range [first,last)
last not included .

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

plz give your valuable feedback