0

I am creating a template class with a list object as a private member:

 .
 .
 .
 private:

list<E> listObject;

 };

The first constructor has to create a list object with capacity of 10. How would you do that?

 template<class T, class E>
 Queue<T,E>::Queue()
 {
listObject.resize(10); 

 }

or

 template<class T, class E>
 Queue<T,E>::Queue()
 {
listObject = new list<E>(10); 

 }

or any other idea?

user2419831
  • 181
  • 4
  • 11
  • Have you tried to compile and run these yet ? – Ian Cook Nov 04 '13 at 06:37
  • 1
    You might want to read a reference about [`std::list`](http://en.cppreference.com/w/cpp/container/list), especially about the [constructor](http://en.cppreference.com/w/cpp/container/list/list). And after that, read about [`std::queue`](http://en.cppreference.com/w/cpp/container/queue). – Some programmer dude Nov 04 '13 at 06:38
  • I think at this stage it would be more productive to read [a good introductory book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – juanchopanza Nov 04 '13 at 06:39

3 Answers3

1

The most idiomatic option would be to initialize the list with the desired size. This is done in the constructor initialization list:

Queue<T,E>::Queue() : listObject(10) 
{
  ....
}

This will leave you with a list of 10 default constructed objects (whether you actually need that is a different matter).

Note that in C++11 you can initialize data members at the point of declaration. So you could also do this:

template <typename T, typename E> Queue
{
  ....
  list<E> listObject = list<E>{10};
};

More on std::list here.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

There is a constructor for list that takes a size argument. You can call that constructor in your class's constructor using an initializer list

template<class T, class E>
Queue<T,E>::Queue()
:  listObject(10)
{}

If you need information, search and learn about initializer lists. You can read more about the std::list class's constructors on a reference website -- that's what I did here -- although I admit the long series of constructors is a little bit much when you're first getting started.

That page says the following about this constructor, with only a count specified (assuming C++11): "Constructs the container with count value-initialized (default constructed, for classes) instances of T."

NicholasM
  • 4,557
  • 1
  • 20
  • 47
0

Currently, no setting capacity api is provided. Its max-size() returned is a super large integer, just a theorial value. api resize will actually allocate that specified N size elements with default value (or object constructor), not just reserve N elements space.

If u want to support a capacity, maybe you should inherit std::list, maintain a capacity value in your implemented child template class.

Arthur
  • 1