gpt4 book ai didi

c++ - 通过引用传递 vector

转载 作者:行者123 更新时间:2023-11-30 03:43:06 26 4
gpt4 key购买 nike

#include <iostream>
#include <vector>

void init()
{
std::vector<double> b;
b.push_back(10);
return;
}

double mean(double *array, size_t n)
{
double m=0;
for(size_t i=0; i<n; ++i)
{
m += array[i];
}
std::cout<<*array<<std::endl;
return m/n;
}

int test(int *b)
{
int dist;
dist=b[0];
return dist;
}

int main()
{
int x=0;
int y=0;
//double a[5]={1, 2, 3, 4, 5};
std::vector<double> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
std::cout<<mean(&a[0], 5)<<std::endl; // will print 3
init();
y=test(&b[0]);
std::cout<<y<<std::endl;
return 0;
}

我正在尝试检查我是否可以在“init”函数中初始化 vector “b”并在“test”函数中检索值以最终在 main 函数中返回为“y”。这可能吗?这只是探索这种可能性的测试代码。

最佳答案

也许你想要:

std::vector<double> init()
{
std::vector<double> b;
b.push_back(10);
return b;
}

然后在主要部分:

auto b = init();
y = test( &b.at(0) );

当调用 mean 时。获取大小为 a.size() 而不是硬编码 5。并传递 a.data() 而不是 &a[0],那么如果 vector 为空,它就不会崩溃。

关于c++ - 通过引用传递 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36323070/

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