Hi,

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;
               comics.insert(element);

    return 0;
}

Header file as follows

// header file 


    template <class T>
    class library {

    private:

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


    public:

       //Public member functions

       Booklist(){
            sort_status=0;
            list_size=0;
            duplicate=0;
        }


        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;
        list_size++;


        }

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

(lldb) EXC_BAD_ACCESS

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)
{
    v.push_back(new_element);
    list_size++;
}

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.