【问题标题】:Passing a typdef vector of vectors by reference通过引用传递向量的 typedef 向量
【发布时间】:2012-08-31 17:14:09
【问题描述】:

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

#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)
{

}

【问题讨论】:

  • +1 以获得完整的(但遗憾的是不是最小的)示例程序。见sscce.org

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


【解决方案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&lt; std::vector&lt;float&gt; &gt;。对这样一个变量的赋值会产生一个副本。将其声明为引用类型 points&amp;(或 std::vector&lt; std::vector&lt;float&gt; &gt;&amp;)使用对原始的引用。

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

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

【讨论】:

  • 这解决了我的问题。我将在 tangentVectorFunction 中以一种奇怪的方式改变结构的尺寸,这就是为什么我不使用尺寸。也许使用单一维度仍然有效。当我完成代码时,我会看看我是否可以进行这种优化。
  • 如果您必须更改尺寸,建议的优化会降低效率,因此最好保持原样,直到您确定它会起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
  • 2015-04-24
  • 1970-01-01
  • 2015-12-18
  • 2013-07-07
相关资源
最近更新 更多