ekiim
ekiim

Reputation: 842

Own "Dynamic" Vector Class

i am having trouble making my own dynamic vector class... the final goal is to simulate stacks and queues, with classes over a vector class, and then migrate to make stacks and queues over a linked list, on c++, but i am having trouble making the vector class...

because i can't make a variable with a default value, i am assigning them on the constructor, but, it seams that it doesn't work, this way... and i really don't want to use the of the standard library any ideas?

my idea was to declare the array in the constructor and then copy it to the pointer declare on the class but it does int work... i can only get the value of the first element, but not the rest...

    class Vector{
    private:
        int *arr;
        int size;
        int inside;
    public:
        Vector(int);
        int length();       // Largo del Arreglo
        int count();        // Numero de elementros adentro
        bool empty();       // Vacio
        bool full();        // Lleno
        int at(int);        // Revisa el N elemento
        int get(int);       // Regresa el n elemento
        bool put(int, int); // Inserta elemento X en n posicicion
        void clean();

};
/// Clase Vector
Vector::Vector(int x){ // Constructor
    int vec[x];
    arr=vec;
    size=x;
    inside=0;
}
// Estado del Vector
bool Vector::empty(){
    if(inside==0){
        return true;
    }
    return false;
}
bool Vector::full(){
    if(inside==size){
        return true;
    }
    return false;
}
int Vector::length(){
    return size;
}
int Vector::count(){
    return inside;
}
// Manipulacion de Datos
int Vector::get(int x){
    int y=at(x);
    put(0,x);
    inside = inside-2;
    return y;

}
int Vector::at(int n){
    int i=arr[n];
    return i;
}
bool Vector::put(int x, int p){
        arr[p]=x;
        inside++;
        return true;
}
void Vector::clean(){
    for(int i=0;i<length();i++){
        put(0,i);
    }
}

Upvotes: 1

Views: 649

Answers (1)

WhozCraig
WhozCraig

Reputation: 66194

This isn't going to work:

int vec[x];
arr=vec;

You're assigning a member variable the address of an automatic local variable that will leave scope on function exit. Accessing it from then on is undefined behavior. Worse, this isn't even portable, as it relies on a compiler extension for variable-length-arrays, something not support by the C++ standard.

You need to dynamically allocate your base vector using operator new [] From that you will also need to properly implement a destructor, assignment operator and a copy constructor (and if going for the full gambit, move-assignment and move-construction) to properly comply with Rule of Three/Five semantics.

Upvotes: 4

Related Questions