ozdm
ozdm

Reputation: 153

Passing reference of vector of objects as arguments in C++

I'm trying to build a function in which an argument is a reference to a vector of objects. In this case name of the object is 'obj', it is an instance of the class 'Example' and it is a vector as defined in vector class. Object have members like x, y and z.

The reason I'm trying with passing references is because I want to change the value of obj.z by making use of obj.x and obj.y from inside of the function.

    #include <vector>
    #include <iostream>
    using namespace std;

    class Example{
    public:

        double x;
        double y;
        double z;

        Example()
        : x(0.0),y(0.0){
        }
    };

    void calculate(Example &obj, int M) {
        for(int i = 0; i < M; i++) {
            obj[i].z = obj[i].x * obj[i].y;
        }
    }

    int main() {
        vector<Example> obj;
        int N = 10;
            calculate(obj, N);           
    }

When I run this, I get the following errors:

Inside of the function I have: "Type 'Example' does not provide a subscript operator." I google'd it and saw that it is related to operator overloading and usage of references. The solution is probably related to dereferencing my object reference inside of the function, but I wasn't able to manage this one right currently.

And the second error is outside of the function, inside the main() at the line where I call the function: "No matching function for call to 'calculate'". Here, I assume the error is related to the fact that obj is not just an object but a vector of objects, so I should change the argument somehow. But I haven't been able to correct this one up to now as well.

So, to summarize, I want to pass a vector of objects to a function as reference, because I want to be able to change a member of the object inside of the function.

Thank you in advance.

Upvotes: 2

Views: 6289

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254771

I want to pass a vector of objects to a function as reference

So do that:

void calculate(vector<Example> &obj) {
    for(int i = 0; i < obj.size(); i++) {
        obj[i].z = obj[i].x * obj[i].y;
    }
}

int main() {
    vector<Example> obj;
    // put some values into it...

    calculate(obj);
}

Upvotes: 2

mfkw1
mfkw1

Reputation: 1161

obj[i]

'obj' isn't an array. You need to declare it as:

void calculate(Example* obj, int M)

And rather

void calculate(vector<Example>& v)

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258698

I believe you wanted your function to be

void calculate(vector<Example> &obj, int M)

and not

void calculate(Example &obj, int M)

Upvotes: 0

Related Questions