use function inside of loop which returns vector

Question

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:

  • Does v actually allocated inside of myfun every time it is called?
  • If it does, what happens to old v?
  • Also, is it better to use just use address like void myfun(some_args, vector<double> &v) for output argument v?

Show source
| function   | c++   | stdvector   2017-01-06 12:01 2 Answers

Answers ( 2 )

  1. 2017-01-06 12:01

    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);
        }
    }
    
  2. 2017-01-06 12:01

    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.

◀ Go back