-2

I am having a very difficult time using push_back on a template object. Can anyone explain why this works

    list<int> mylist;
    int myInt;
    mylist.push_back(myInt);

but this won't.

    list<KeyValuePair<T>> mylist;
    int myInt;
    mylist.push_back(myInt);
genpfault
  • 51,148
  • 11
  • 85
  • 139
T3nt4c135
  • 104
  • 8

2 Answers2

3

A list is a list of some templated objects. You instantiate a list of int objects with:

list<int> mylist;

This list now 'knows' it will be managing int objects.

One of the list methods is push_back() wich adds objects of the templated object type to the end of the list.

You instantiate a list of KeyValuePair objects with:

list<KeyValuePair<T>> mylist;

This second list is for managing KeyValuePair objects

Now if you try to add int objects to a list of KeyValuePair objects, this will fail because this list is a list of KeyValuePair objects, not int objects.

anneb
  • 5,510
  • 2
  • 26
  • 26
0

The second list is declared to store object of type KeyValuePair<T>. Thats why its not allowing your to push_back() of type int.

MKR
  • 19,739
  • 4
  • 23
  • 33