通过引用传递向量
Passing a vector by reference
#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]
,那么如果向量为空,它就不会崩溃。
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 创建引用向量的优雅方式
- C++重新引用向量中的值
- 很好的语法来获取对向量/数组数据的大小引用?
- 如何返回向量的常量引用?
- 取消引用向量时出现问题
- 为什么通过 vector<reference_wrapper> 的元素删除引用的值<T>不会使向量无效?
- 通过引用传递向量是请求 std::分配器
- 从类返回引用向量
- 返回两个向量 – 使用引用还是元组?
- 在C++中通过引用传递向量数组
- 引用向量中的特定索引
- 如何告诉自动推断向量<bool>元素的非引用类型
- 如何在方法主体中返回声明向量的引用?
- 向量引用C++
- 在向量引用上调用 vector::reserve()
- 如何创建一个同时接受数组和向量引用的函数模板
- 如何做列表的向量引用列表中的值
- c++向量引用转换
- 最方便的表示向量引用的向量的方法