Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I get from front() of empty std container?

Tags:

c++

stl

People also ask

What does front return C++?

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.

How to get first element of a vector C++?

vector::front() This function can be used to fetch the first element of a vector container.

How do you return an empty list in C++?

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