The code uses q.peek(), but std::queue does not have a peek() method.
Step 2: Identify correct method
The correct method to access the front element is q.front().
Final Answer:
Using q.peek() which is not a valid method -> Option C
Quick Check:
std::queue peek method = front() [OK]
Hint: Use front(), not peek(), to access front element [OK]
Common Mistakes:
Using peek() method
Assuming peek() exists
Ignoring compiler errors
5. Given a queue q containing integers, write a C++ function int peekFrontOrDefault(std::queue<int>& q, int defaultVal) that returns the front element if the queue is not empty, or defaultVal if it is empty. What is the correct implementation?
hard
A. return q.front();
B. if (q.empty()) return q.front(); else return defaultVal;
C. if (q.size() > 1) return q.front(); else return defaultVal;
D. if (!q.empty()) return q.front(); else return defaultVal;
Solution
Step 1: Check if queue is empty
Use q.empty() to verify if queue has elements.
Step 2: Return front or default value
If not empty, return q.front(); otherwise, return defaultVal.
Final Answer:
if (!q.empty()) return q.front(); else return defaultVal; -> Option D
Quick Check:
Check empty before front() to avoid errors [OK]
Hint: Always check empty before front() to avoid errors [OK]
Common Mistakes:
Not checking empty before front()
Wrong condition on size
Returning front when empty
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.