I am trying to pass a vector of vectors by reference. I have typdefed the datatype and it seems to me that I am getting a copy, not a reference. I couldn’t find figure out any valid syntax to do what I want here. Suggestions?
#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)
{
}
Assuming your typedef remains:
Your prototype for passing by reference would look like this:
Your
pointstype is just a value type, and is equivalent tostd::vector< std::vector<float> >. Assignment to such a variable makes a copy. Declaring it as a reference typepoints&(orstd::vector< std::vector<float> >&) uses a reference to the original.It certainly doesn’t make a difference in the scope of your problem, but you might consider simply using a one dimensional vector. You save a little bit on memory allocations, deallocations, and lookups this way. You’d use: