Wednesday, April 18, 2012

Custom Vector Template - Strings

I am attempting to read in a list of strings from the keyboard to a custom vector template that I wrote, however for some unknown reason, the program ALWAYS crashes after the second or third input when I attempt to write to or read the vector object.



Note: The entire point of the assignment is to write your own custom vector class and I am not allowed to use any feature provided by the C++ STL, such as arrays.



edit: Everything works without fault if I make it an int or char vector, but it needs to do all 3.



main.cpp



#include <iostream>
#include "myvector.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>

using namespace std;

int main()
{
myvector<string> vec;

string tmp;

while(1) {
cin >> tmp;
if(tmp=="q"){
break;
}
vec.push_back(tmp);
}

cout << "You have entered " << vec.size() << " elements. These are:" << endl;

for(int i=0;i<vec.size();i++) {
cout << vec[i] << endl;
}

return 0;
}


myvector.h



#ifndef MYVECTOR_H
#define MYVECTOR_H

#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

template<class T>
class myvector
{
public:
myvector();
myvector(const myvector&);
~myvector();
void push_back(const T&);
int size();
T operator[](int);
myvector& operator=(const myvector&);
protected:
private:
int vsize,maxsize;
T* array;
void alloc_new();
};

template<class T>
myvector<T>::myvector()
{
maxsize=8;
array=(T *)malloc(maxsize*sizeof(T));

if (array == NULL) {
cout << "Memory failure";
}
vsize=0;
}

template<class T>
myvector<T>::myvector(const myvector& v)
{
maxsize=v.maxsize;
vsize=v.vsize;
array = (T *)malloc(maxsize*sizeof(T));
for(int i=0;i<v.vsize;i++) {
array[i]=v.array[i];
}
}

template<class T>
myvector<T>::~myvector()
{
free(array);
}

template<class T>
void myvector<T>::push_back(const T& i)
{
if(vsize>=maxsize) {
alloc_new();
}
array[vsize]=i; //CRASHES KEEP HAPPENING HERE I THINK
vsize++;
}

template<class T>
T myvector<T>::operator[](int i)
{
return array[i];
}

template<class T>
void myvector<T>::alloc_new()
{
maxsize=vsize*2;
T* tmp=(T *)malloc(maxsize*sizeof(T));
for(int i=0;i<vsize;i++) {
tmp[i]=array[i];
}
free(array);
array=tmp;
}

template<class T>
int myvector<T>::size()
{
return vsize;
}

template<class T>
myvector<T>& myvector<T>::operator=(const myvector& v)
{
if(this!=&v) {
maxsize=v.maxsize;
vsize=v.vsize;
delete[] array;
array = (T *)malloc(maxsize*sizeof(T));
for(int i=0;i<v.vsize;i++) {
array[i]=v.array[i];
}
}
return *this;
}

No comments:

Post a Comment