I'm trying to learn templates. I want to pass strings and integers via objects. I made it as a template because my program should support both strings and integers.

 // Main Function

 int main()
    string element;
    library <string> comics;

               cout << "\nPlease type in the element: \n";
               cin >> element;

    return 0;

Header file as follows

// header file 

    template <class T>
    class library {


        vector <T> v;
        int sort_status;
        int list_size;
        int duplicate;


       //Public member functions


        void insert(T const&);


    // Function definition for adding new element to the end of the list

    template <class T>
    void library <T>::insert(T const& new_element){

        v[0] = new_element;


What am i doing wrong? Program compiles but when i enter a string as input, i get this error.


Any help would be appreciated. Thanks

To add an element to a vector, you need to use the push_back function. The error comes from the fact that when you are accessing v[0] when the vector is empty, you will get an error because there is nothing to access. Your insert function could look like that:

template <class T>
void library <T>::insert(T const& new_element)

Also, note that the list_size is redundant because the vector objects already keep track of how many elements it has, i.e., you could just use v.size() to know how many elements you have.

Great. That solved the problem. Thank you very much.

Can i use arrays instead of vector to store strings? If yes, then how would the syntax change?

How do you think it should change? Arrays are kind of like vectors, but they don't resize automatically, so you need to pre-allocate a size, and when the size needs to be increased, you need to re-allocate the array. In any case, C-style arrays don't have methods like "push_back", "pop", etc. You need to deal with these behaviors manually.

Anyway, the answer to your question is yes. You figure out the syntax and code, and then when you run into problems, post the code here with the problems you are having.

sure. I'm definitely going to give a try. Thanks all!