Rrakib
Rrakib

Reputation: 200

How to store class pointer in a Vector?

I have a class that stores some symbols.

class SymbolInfo{   
public:
    string name;
    string type;
    string token;
    int num;
    char ch;
    float fl;   
    int arrSize;
    int array_index_holder;
    SymbolInfo *next;
    Function *func;
    SymbolInfo* myarray;
    SymbolInfo(){
        name="";
        type="";
        token="";
        next = NULL;
        arrSize = -1;
        array_index_holder = -1;

    }

    SymbolInfo(string name, string type){
        this->name = name;
        this->type = type;
        token="";
        next = NULL;
        arrSize = -1;
        array_index_holder = -1;


    }

    string getname(){
        return name;
    }

    void setname(string name){
        name = name;
    }

    string gettype(){
        return type;
    }

    void settype(string type){
        type = type;
    }




};

I wanted to make an array of symbols. So I use this class in a Vector and created this:

Vector<SymbolInfo*>array;

And with the integer size, I was trying to create an array like this:

SymbolInfo *s= table->LookUp($3->name);
$3->type = dataType;
    table->Insert($3->name, $3->type);
    s = table->LookUp($3->name);
    s->token = "ARRAY";
    int size = $5->num;
    for(int i=0;i<size;i++){
            array[i].push_back(*s);
    } 

$3 and $5 are SymbolInfo type pointer(it's for YACC/BISON) After executing this I got this error:

parser.y: In function ‘int yyparse()’:
parser.y:200:12: error: request for member ‘push_back’ in ‘array.std::vector<_Tp, _Alloc>::operator[]<SymbolInfo*, std::allocator<SymbolInfo*> >(((std::vector<SymbolInfo*>::size_type)i))’, which is of pointer type ‘SymbolInfo*’ (maybe you meant to use ‘->’ ?)
   array[i].push_back(*s);
            ^

What am I doing wrong? How to resolve this problem?

Upvotes: 0

Views: 808

Answers (2)

Kryler
Kryler

Reputation: 111

If array is a vector than just call push_back on it. It will put the element at the back of the vector. If you use the [] operator it evaluates to reference to the item in the vector in this case a pointer to some Symbol table info. If you want to store something in the vector at index i given the vector has an index i then use the line of code

vector[i] = something;

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

The pointer is just called s, and the vector is just called array.

So:

array.push_back(s);

The expression array[i] gives you one of the pointers already in the vector, and the expression *s gives you whatever s points to (it is a dereference operation).

Upvotes: 0

Related Questions