通过引用传递向量

Passing a vector by reference

本文关键字:向量 引用      更新时间:2023-10-16
#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"函数中初始化向量"b"并在"test"函数中检索值,最终在主函数中返回为"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],那么如果向量为空,它就不会崩溃。