Vivid Debugger
Vivid Debugger

Reputation: 83

Implementing a Vector in a Queue

The vector displays just fine when it doesn't need to use the grow function, but as soon as the grow function is initialized the display for the vector goes crazy, here are the results

Output:

Grow function not initialized:

R

B

C

E

R

B

Grow function initialized by adding another element 'E' in this case

R

B

R

B

#include<iostream>

using namespace std;

class vector{

    public:
        void add(char);
        void display();
        void setSizes();

    private:
        void grow();
        int growthSize;
        int maxSize;
        int currSize=0;
        char * arr;

};


//initializes private variables
void vector::setSizes(){
    growthSize=2;
    maxSize= 7;
    arr = new char[maxSize];
}



//grows the vector
void vector::grow(){
    int *temp = new int[maxSize];
    //Makes copy of array
        for(int i=0;i<maxSize;i++){
            temp[i]=arr[i];
        }

    delete arr;

    int *arr = new int[maxSize+growthSize];
        for(int i= 0; i<maxSize; i++){
        arr[i]= temp[i];
        }

    delete temp;
    maxSize= maxSize + growthSize;
    cout<< "The array grew by " << growthSize << " elements."<< endl;
    }



//adds to the vector
void vector::add(char insert){
    arr[currSize]=insert;
    currSize++;
    if(currSize == maxSize){
        grow();
    }

}



void vector::display(){
    for(int i=0;i<currSize;i++){

        cout<<arr[i]<< endl;

    }

}


 int main(){

    vector bill;
    bill.setSizes();
    bill.add('R');
    bill.add('B');
    bill.add('C');
    bill.add('E');
    bill.add('R');
    bill.add('B');
    bill.add('E');

    bill.display();






}

Upvotes: 0

Views: 930

Answers (1)

The Dark
The Dark

Reputation: 8514

This line

int *arr = new int[maxSize+growthSize];

hides the declaration of arr in the class, so you are then just working with a local variable.

Upvotes: 3

Related Questions