Maram
Maram

Reputation: 37

Pointers and pass by reference c++

In my main, I call the function compute_entropy and I give it a vector like this: float entropy = h.compute_entropy(input_pic[0], & Symbol_table);

In Implementing the function itself (in h.cpp), I should not change the parameter it takes which is vector* prob.. how can I access the data of prob?

float compute_entropy(vector<Symbol>* prob)
{

    float ent = 0;
    vector<Symbol>* prob;


    for (int i = 0; i < prob.size(); i++)  //GIVES ERROR
    {
        ent +=    (prob.at(i).freq)   *   log2(  1 / (prob.at(i).freq)  );
    }
}

Upvotes: 0

Views: 86

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

Because type of prob is Vector<Symbol> *, you actually need to dereference it first before accessing member. It looks like (*prob).at(i).freq.

*(A).B can also be written as A->B, so instead of (*prob).at(i).freq, you can write prob->at(i).freq. (With similar argument prob.size() becomes prob->size())

Doing it in cleaner way
Because you never change the contents of your vector you can make the argument constant.

float compute_entropy(const vector<Symbol>* prob)

Now as we know pointers are evil, let's replace pointer with a reference.

float compute_entropy(const vector<Symbol> &prob)
{

    float ent = 0;

    for (int i = 0; i < prob.size(); i++)  //GIVES ERROR
    {
        ent +=    (prob.at(i).freq)   *   log2(  1 / (prob.at(i).freq)  );
    }
}

While calling this, if you were calling with vector, drop the & from the argument, and if you were calling with a vector pointer, dereference it with a *.

Upvotes: 3

Pandrei
Pandrei

Reputation: 4951

vector<Symbol>* prob;    
for (int i = 0; i < prob.size(); i++)  //GIVES ERROR
.....

Because prob is a pointer, you need to use the -> operator

for (int i = 0; i < prob->size(); i++)

Upvotes: 0

Related Questions