When i print data stored in a queue it also dequeue these data...
can someone provide me hints on how to print data without dequeue...printing
should only display data stored in that queue........

Dani AI

Generated

A quick summary of the problem and a practical way to print a queue without removing elements. described that printing currently calls pop() and destroys the data. Replies by and point toward copying or traversing, but if the code uses std::queue there is a cleaner option that avoids a full copy and still does not modify the queue.

std::queue keeps its elements in a protected member container named c. Deriving a thin wrapper that returns a const reference to that container exposes iterators for read-only traversal without dequeuing or duplicating the data. Example:

template<typename T, typename Container = std::deque<T>>
struct PrintableQueue : std::queue<T, Container> {
    const Container& view() const { return this->c; }
};

Usage:

PrintableQueue<int> q;
// push items into q
for (const auto& item : q.view())
    std::cout << item << '\n';

Notes and cautions: this relies on the fact that the underlying container stores elements in queue order (default std::deque does); it is O(n) to traverse but does not allocate a full copy. It exposes only const access so the queue itself is not modified, but it is not thread-safe—protect with a mutex if other threads may push/pop concurrently. If the queue implementation is custom, add a const traversal method or implement iterators inside the class instead of exposing internals. For reference on std::queue internals, see std::queue on cppreference.

Recommended Answers

All 3 Replies

Have you tried copying your Queue into a temporary Queue, and printing the data of the temporary Queue instead?

Actually, the smarter solution would be to return an iterator of the Queue and traverse through it and get the output of the data inside.

Yeap, Copy the pointer to the first node. And move it to the last node and print the data as you traverse.
And did you really understand how your dequeue algorithm works?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.