gpt4 book ai didi

c++ - 在返回 vector 的循环内使用函数

转载 作者:行者123 更新时间:2023-11-30 05:18:44 25 4
gpt4 key购买 nike

我有一个函数 myfun这将返回一个 vector 。

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

然后,我将在循环中使用它来更新v并使用 v得到一些结果。

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);
}
}

所以,我的问题是:

  • 是否v实际上分配在myfun里面每次调用?
  • 如果是,旧的v 会怎样? ?
  • 此外,是否最好只使用像 void myfun(some_args, vector<double> &v) 这样的地址?对于输出参数 v

最佳答案

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 &v) for output argument v?

是的,根据您的操作,最好通过引用传递 vector 。

你可以这样做

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);
}
}

关于c++ - 在返回 vector 的循环内使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com