About the back() function of std :: queue

Please help me, why c ++ stl defines the back() function for std :: queue to get the value of the last element, while the queue I have been learning does not define this.
Thank you everyone.
Last edited on
Your question makes no sense.

There is no one, true, correct queue class. Some queue classes might have a function to get the item at the back. Some might not.

The one defined by the STL does. The one you have been looking at does not. There is no "why"; it's just how they were made.
There are two basic queues. LIFO and FIFO. Someone will jump in to mention priority queues (and a long list of others), but the two BASIC queues are LIFO and FIFO.

LIFO is a stack. You push front/pop front. You could just as easily push back/pop back. The results would be identical.

FIFO is a pipe. You push front/pop back. You could just as easily push back/pop front.

Same results either way. What they call it doesn't really matter.

Those can be done with dequeue.
Last edited on
> why c ++ stl defines the back() function for std :: queue to get the value of the last element

The interface of std::queue<> was decided on prior to C++11; before move semantics, before variadic templates and emplace were available. Under C++98, providing access to the element at the back of the queue allowed certain operations to be more efficiently performed.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// C++98
#include <queue>
#include <list>
#include <string>

int main()
{
    std::queue< std::list< std::string > > q ;
    // add some items to the queue ...

    // add list containing "abc", "def", "ghi" to the queue
    {
        // without the queue providing back()

        // 1. make a list
        std::list<std::string> lst ;
        lst.push_back("abc") ;
        lst.push_back("def") ;
        lst.push_back("ghi") ;

        // 2. copy the list into the queue
        q.push(lst) ;

        // 2. destroy the list
    }

    {
        // using back()

        // 1. add en empty list to the queue
        q.push( std::list<std::string>() ) ;

        // 2. add the strings to the list at the back of the queue
        q.back().push_back("abc") ;
        q.back().push_back("def") ;
        q.back().push_back("ghi") ;
    }
}

Thank you everyone for giving me the answer.
Topic archived. No new replies allowed.