通过引用传递向量的typdef向量
Passing a typdef vector of vectors by reference
我正试图通过引用传递一个向量。我已经输入了数据类型,在我看来,我得到的是一个副本,而不是引用。我在这里找不到任何有效的语法来做我想做的事情。建议?
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
#define __DEBUG__
using namespace std;
//Define custom types and constants
typedef std::vector< std::vector<float> > points;
//Steup NAN
float NaN = 0.0/0.0; //Should be compiler independent
//Function prototypes
void vectorFunction(float t0, float tf, points data );
//Global constants
string outFilename = "plotData.dat";
int sampleIntervals = 10000; //Number of times to sample function.
int main()
{
ofstream plotFile;
plotFile.open(outFilename.c_str());
points data;
vectorFunction( 0, 1000, data );
#ifdef __DEBUG__
//Debug printouts
cout << data.size() << endl;
#endif
plotFile.close();
return 0;
}
void vectorFunction(float t0, float tf, points data )
{
std::vector< float > point(4);
float timeStep = (tf - t0)/float(sampleIntervals);
int counter = floor(tf*timeStep);
//Resize the points array once.
for( int i = 0; i < counter; i++)
{
point[0] = timeStep*counter;
point[1] = pow(point[0],2);
point[2] = sin(point[0]);
point[3] = -pow(point[0],2);
data.push_back(point);
}
#ifdef __DEBUG__
//Debug printouts
std::cout << "counter: " << counter
<< ", timeStep: " << timeStep
<< ", t0: " << t0
<< ", tf: " << tf << endl;
std::cout << data.size() << std::endl;
#endif
}
void tangentVectorFunction(float t0, float tf, points data)
{
}
假设您的typedef仍然存在:
typedef std::vector< std::vector<float> > points;
您的参考传递原型如下所示:
void vectorFunction(float t0, float tf, points& data);
void tangentVectorFunction(float t0, float tf, points& data);
您的points
类型只是一个值类型,它等效于std::vector< std::vector<float> >
。对这样一个变量的赋值会产生一个副本。将其声明为引用类型points&
(或std::vector< std::vector<float> >&
)将使用对原始文件的引用。
这当然不会对你的问题范围产生影响,但你可以考虑简单地使用一维向量。通过这种方式,您可以节省一点内存分配、释放和查找。你会使用:
point_grid[width * MAX_HEIGHT + height] // instead of point_grid[width][height]
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 通过引用传递向量的typdef向量