The C++ function std::queue::front() returns a reference to the first element of the queue. This element will be removed after performing pop operation on queue. This member function effectively calls the front member function of underlying container.
vector::front() This function can be used to fetch the first element of a vector container.
list::empty() is an inbuilt function in C++ STL which is declared in header file. list::empty() checks whether the given list container is empty(size is 0) or not, and returns true value if the list is empty and false if the list is not empty.
You get undefined behaviour - you need to check that the container contains something using empty() (which checks if the container is empty) before calling front().
You get undefined behaviour.
To get range checking use at(0). If this fails you get a out_of_range
exception.
Yes, you can use 'at' like Graham mentioned instead of using front.
But, at(0) is only available for some containers - vectors, deque and not for others - list, queue, stack. In these cases you've to fall back on the safety of the 'empty' check.
You've always have to be sure your container is not empty before calling front() on this instance. Calling empty() as a safe guard is good.
Of course, depending on your programm design, always having a non-empty container could be an invariant statement allowing you to prevent and save the call to empty() each time you call front(). (or at least in some part of your code?)
But as stated above, if you want to avoid undefinied behavior in your program, make it a strong invariant.
Undefined Behaviour
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