views:

65

answers:

3

I have declared:

queue<int, list<int> > Q

After a series of calls:

Q.push(37);
Q.pop();
Q.push(19);
Q.push(3); 
Q.push(13); 
Q.front(); 
Q.push(22); 
Q.push(8);
Q.back();

I get: 19->3->13->22->8->NULL

What I don't get is what the calls to Q.front() and Q.back() do. From what I understand, they return a reference to the first or last elements respectively, but I dont see how my list would be any different had those calls not been made. Do they have any effect?

Sorry if this seems trivial, but I'm trying to figure out of those calls have a purpose, or of my professor is just trying to screw with me.

+9  A: 

They give you a reference but if you want to do something with it then you have to use that reference.

e.g.

Q.push(37);
Q.push(19);
Q.front() = 8;

Then you should have...

8,19

Merely calling Q.front() or Q.back() on their own line has no effect. These are generally referred to as accessor functions, they give you access to a value (which you can sometimes modify if you want) but don't themselves modify the underlying data structure.

Pace
+1  A: 

They are useful to peek values in the queue without having to remove and put them back.. it may be useful in certain situations!

For example, how would you do to decide to remove the first element from the queue just if it's greater than X?

Without front() you would have to remove it from the queue, check the value, and then use it or put it back if condition is not satisfied. With this accessor method instead you can easily check it before altering the underlying data structure.

Jack
+2  A: 

Nothing is done with the return value of those calls and they do not alter the queue itself, so you are correct in saying that your queue would have been the same without them. Your compiler may have noticed this as well and optimized them away.

bta