Nayeem Hossain
Nayeem Hossain

Reputation: 13

Why this implementation of vector doesn't work for string?

I've tried this implentation to do same as vector stl. This implementation works for int,float,double and char. But it doesn't work for string. It shows runtime error for string.Can you please fix the problem?
Here is the github repository link: https://github.com/Nayeem-CSE-CoU/DataStructure/blob/main/vector.cpp I've also included the code here:

#include<bits/stdc++.h>
using namespace std;
template<class T>
class Vector
{
private:
    T *ptr;
    int pos=0;
public:
    Vector()
    {
        ptr=new T();

    }
    Vector(int n)
    {
        ptr=new T();
        pos=n;
    }
    Vector(int n,T val)
    {
        ptr=new T();
        for(int i=0;i<n;i++)
        {
            *(ptr+pos)=val;
             pos++;
        }
    }
    void push_back(T n)
    {
        *(ptr+pos)=n;
         pos++;

    }
    void pop_back()
    {
        pos--;
        delete (ptr+pos);
    }

    T const operator [] (int i)const
    {
        
       return *(ptr+i);
         
    }
    T &operator[](int i)
    { 
        return *(ptr+i);
       
    }
    int size()
    {
        return pos;
    }
    T* begin()
    {
        return ptr;
    } 
    T* end()
    {
        return (ptr+pos);
    }

};
int main()
{
    
     Vector<string> sf;
    sf.push_back("kkk");
    sf.push_back("jjj");
    sf.push_back("Nayeem");

    
     for(auto x:sf)
     cout<<x<<" ";
     cout<<endl;

    
    return 0;

}

Upvotes: 0

Views: 380

Answers (2)

SherAndrei
SherAndrei

Reputation: 627

Let's try to understand what is happening here

    Vector<string> sf;   // <- calls Vector<string>::Vector() creating one new string str
    sf.push_back("kkk"); // <- places string "kkk" to the str
    sf.push_back("jjj"); // <- trying to place new string "jjj" to a place, that was never yours => results in the runtime error
    sf.push_back("Nayeem"); // <- and again
    
     for(auto x:sf)
     cout<<x<<" ";
     cout<<endl;

std::vector is a dynamic array

You need to manage your memory on more advanced level. Try to read about it here

Upvotes: 0

eerorika
eerorika

Reputation: 238351

ptr=new T();

Your vector implementation creates a single dynamic object.

void push_back(T n)
{
    *(ptr+pos)=n;
     pos++;

}

Your vector implementation attempts to access the pointer to a single object as if it was a pointer to an array of objects, accesses outside the bounds of that single object, and behaviour of the program is undefined.

This implementation works for int,float,double and char

It doesn't work for any type.

Upvotes: 6

Related Questions