Creating a standard pointer queue in C ++

Say I have a queue of integers,

#include <iostream> #include <queue> using namespace std; int main() { int firstValToBePushed = 1; queue<int> CheckoutLine; CheckoutLine.push(firstValeToBePushed); cout << CheckoutLine.front(); return 0; } 

How can I do almost the same thing using a queue that contains pointers to integers, as opposed to integers, as it currently does above. I plan to make a loop to make a few values, but this is just a simpler example.

Thanks,

+4
source share
4 answers

If this is for lifecycle management, then:

 std::queue<std::shared_ptr<int>> CheckoutLine; CheckoutLine.push(std::make_shared<int>(firstValeToBePushed)) 

If your queue looks like a proxy server, and someone really owns the lifetime of the objects, then definitely:

 std::queue<std::reference_wrapper<int>> CheckoutLine; CheckoutLine.push(firstValeToBePushed) 

If you do not put the queue anywhere and inside it, then keeping the pointers in order, like the others.

However, NEVER NEVER provides a client with a collection of pointers that the worst thing you can do is when you leave the burden of managing life time on them and that messier in the collections.

Of course, for primitive types or POD just copying is in order, there is no need to store pointers. Moving semantics makes it easy even for non-PODs if you don’t have a complex design or you cannot implement move semantics.

#include <functional> for std::reference_wrapper and #include <memory> for std::shared_ptr , std::unique_ptr and friends. I assume that you have access to a modern compiler.

+4
source

Adding a loop for you.

 #include <iostream> #include <queue> using namespace std; int main() { queue<int*> theQueue; char c = 'n'; while (c == 'n') { cout << "Enter \'n\' to add a new number to queue ( \'q\' to quit):"; cin >> c; if ( c == 'q') { break; } else { int num; cout << "Enter an integer and press return: "; cin >> num; theQueue.push(new int(num)); } } while( !theQueue.empty() ) { cout << theQueue.front() << ": " << *theQueue.front() << endl; delete theQueue.front(); theQueue.pop(); } return 0; } 
+2
source
 #include <iostream> #include <queue> using namespace std; int main() { int value = 1337; int* firstValeToBePushed = &value; queue<int*> CheckoutLine; CheckoutLine.push(firstValeToBePushed); cout << *(CheckoutLine.front()) << "is at " << CheckoutLine.front(); return 0; } 
0
source

I'm not sure I understood, maybe you want to do this:

 #include <iostream> #include <queue> using namespace std; int main(){ int firstValueToBePushed = 1; queue<int *> CheckoutLine; CheckoutLine.push(new int(firstValueToBePushed)); cout << *CheckoutLine.front() << endl; return 0; } 
0
source

All Articles