Home > Net >  Issues with outputs for dynamic arrays
Issues with outputs for dynamic arrays

Time:05-09

I'm working with a template class for dynamic arrays, and my code has compiled successfully, however my get function for a given element in the dynamic array does not seem to be working. Nothing seems to be outputted whenever I output the function, but this doesn't make sense, because my size function works fine, and shows that there is indeed something within the array, I just can't output it. Can anyone help?

#include <iostream>
using namespace std;

template <class T>
class Wrapper{
private:
    T* array;
    int size;
public:
    Wrapper(){
        array = NULL;
        size = 0;
    }
    int returnSize(){
        return size;
    }
    void addEntry(string input){
        if(returnSize()==0){
            array = new string[returnSize() 1];
            array[returnSize()] = input;
            size =1;
        }
        else{
            T* newArray = new T[returnSize() 1];
            for(int i = 0; i<returnSize(); i  ){
                newArray[i] = array[i];
            }
            newArray[returnSize()] = input;
            size =1;
            string *array = new string[returnSize()];
            array = newArray;
        }
        
    }

    bool deleteEntry(string input){
        int mySize = returnSize();
        string* testArray = new string[mySize];
        for(int i = 0; i<mySize; i  ){
            if(array[i]==input){
                return true;
                break;
            }
        }
        string*newArray = new string[mySize-1];
        for(int i = 0; i<mySize; i  ){
            if(array[i]!=input){
                newArray[i =1] = array[i];
        }
        }
        delete[]array;
        array = newArray;
        return true;
        
    }
    string getEntry(int input){
        if(input>size){
            return NULL;
        }
        return this->array[input];
    }
    void operator=(const Wrapper w){
        this->size = w.returnSize();
        string *newArray = new string[size];
        for(int i = 0; i<size; i  ){
            newArray[i] = w.getEntry(i);
        }
        this->array = newArray;
    }
    ~Wrapper(){
        delete[] array;
    }

};

int main(){
    Wrapper<string> w;
    w.addEntry("sam");
    w.addEntry("Josh");
    w.addEntry("tom");
    cout<<"Here"<<endl;
    cout<<w.returnSize();
    for(int i = 0; i<<w.returnSize(); i  ){
        cout<<w.getEntry(i);
    }
}

CodePudding user response:

Just to collect the findings, if you delete this line from addEntry:

           string *array = new string[returnSize()];

and change your final for loop to:

    for(int i = 0; i < w.returnSize(); i  ){
        cout<<w.getEntry(i)<<"\n";
    }

then this does exactly what you expect. I've run it myself.

  • Related