我试图通过引用传递向量的向量。我已经简化了数据类型,在我看来,我得到的是副本,而不是参考。我无法找到任何有效的语法来做我想要的事情。建议?
#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)
{
}
答案 0 :(得分:1)
假设你的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]