Dohyun
Dohyun

Reputation: 642

use function inside of loop which returns vector

I have a function myfun which will return a vector.

vector<double> myfun(const size_t k, const size_t i){
    vector<double> v(k);
    // do some computation with remaining arguments
    return v;
}

Then, I will use it in the loop to update v and use v to get some result.

int main(){
    size_t N = 100; // iteration size
    size_t n = 10; // size of v
    vector<double> result(N);
    vector<double> v(n);
    for(size_t i = 0; i<N; i++){
        v = myfun(n,i); // compute for each iteration
        result[i] = compute_some_value(v);
    }
}

So, my question is:

Upvotes: 1

Views: 48

Answers (2)

Reaz Murshed
Reaz Murshed

Reputation: 24211

Does v actually allocated inside of myfun every time it is called?

Yes

If it does, what happens to old v?

When v gets out of scope the destructor is called and the object gets destruct. This is why you don't really have to call destructor of a class explicitly.

Also, is it better to use just use address like void myfun(some_args, vector &v) for output argument v?

It really depends on your use case. If it concerns with memory issues, its better to pass the reference.

Upvotes: 0

Shreevardhan
Shreevardhan

Reputation: 12641

Does v actually allocated inside of myfun every time it is called?

Yes

If it does, what happens to old v?

It gets overwritten.

Also, is it better to use just use address like void myfun(some_args, vector &v) for output argument v?

Yes, it's better to pass vector by reference depending on your operations.

You could do it this way

double compute_some_value(vector<double> & v, const size_t i) {
    v.clear();    // use if required
    // do some computation with remaining arguments and return
}

int main() {
    size_t N = 100; // iteration size
    size_t n = 10; // size of v
    vector<double> result(N), v(n);
    for (size_t i = 0; i < N; i++) {
        result[i] = compute_some_value(v, i);
    }
}

Upvotes: 1

Related Questions