c++ - 通过引用传递 vector 的 typedef vector

标签 c++ vector pass-by-reference typedef

我正在尝试通过引用传递 vector 的 vector 。我已经输入了数据类型,在我看来我得到的是一份拷贝,而不是引用。我在这里找不到任何有效的语法来做我想做的事。有什么建议吗?

#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;

通过引用传递的原型(prototype)如下所示:

void vectorFunction(float t0, float tf, points& data);
void tangentVectorFunction(float t0, float tf, points& data);

你的 points type 只是一个值类型,相当于 std::vector< std::vector<float> > .分配给这样的变量会产生一个拷贝。将其声明为引用类型 points& (或 std::vector< std::vector<float> >& )使用对原件的引用。

它当然不会对您的问题范围产生影响,但您可能会考虑简单地使用一维 vector 。通过这种方式,您可以节省一点内存分配、释放和查找。你会使用:

point_grid[width * MAX_HEIGHT + height] // instead of point_grid[width][height]

关于c++ - 通过引用传递 vector 的 typedef vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12307616/

相关文章:

c++ - 为什么我的 'count leading zero' 程序出现故障?

c++ - 分隔字符串中的不同数据

c# - 与结构的接口(interface),通过使用泛型进行引用

java - JNA 通过引用传递结构帮助

c++ - 未初始化的枚举器默认值

c++ - 内存泄漏 void*

c++ - 在类中使用 vector 创建类

c++ - 如何正确删除 vector 中的对象

c++ - 如何将指针变量作为引用参数传递?

c++ - 多线程环境下的文档锁定