0

I want to create a dynamic queue (using the keyword new) with an underlying data structure of list in c++ but I cannot figure out the syntax for it. What I have so far is:

queue<int, list<int>> myQueue = new queue<int, 

but I cannot figure out what to finish this line with. Can someone help me? Thanks

4
  • You need a space between the two >> (i.e. > >) otherwise the compiler thinks it is the >> operator. Commented Feb 24, 2012 at 21:09
  • 1
    @selalerer: It depends on the compiler/version and the version of the standard that it compiles with. In C++11 the extra space is not required, in C++03 Visual Studio also accepts that. Commented Feb 24, 2012 at 21:25
  • ^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H; Commented Feb 24, 2012 at 21:31
  • Does this work even though the constructor for queue even though the queue constructor is really weird: explicit queue ( const Container& ctnr = Container() ); Commented Feb 25, 2012 at 0:12

1 Answer 1

6

The new instruction returns a pointer, so you don't finish that line at all. You need the variable type to be a pointer if you insist on using new. And the type on the right of new will be the same type as the pointer type of the variable you're initializing.

queue<int, list<int> >* myQueue = new queue<int, list<int> >;

In general, to dynamically allocate any type X, you just write new X. Perhaps you were a little confused because of how complicated the full name of your type is (commas, angle brackets, multiple tokens, etc.). You can simplify it with a typedef to give the name a single-token name:

typedef queue<int, list<int> > int_list_queue;

Then you can write this:

int_list_queue* myQueue = new int_list_queue;

If you don't really need a pointer, then the declaration is simpler:

queue<int, list<int> > myQueue;
// or
int_list_queue myQueue;
Sign up to request clarification or add additional context in comments.

4 Comments

If you need a pointer (but not dynamic storage duration) you may also stick with the last option and &myQueue.
@Nosrettap Note the space between the > characters. Some compilers misinterpret >> as a right-shift operator, panic, and stop compilation. C++11 requires them to handle this right, but until we're all using it you'll need the space.
Does this work even though the constructor for queue even though the queue constructor is really weird: explicit queue ( const Container& ctnr = Container() );
Of course it works. Try it and see. The constructor isn't weird. You can pass an instance of the container class (list, in this case), but if you don't, one is constructed and passed in for you. It's a feature called default parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.