如何返回vector c ++?

时间:2018-02-19 11:31:33

标签: c++ math vector return fstream

我需要一个允许我计算/存储并返回给定间隔的数学表达式值的想法。例如:x^2 - 7 from -5 to 5

我的.cpp文件:

#include <vector>
#include "header.hpp"

double Example::function(double min, double max, double x)
{
    std::vector<double> vector1;

    for(x=min; x<=max; x++)
    {
        result = x * x - 7;
        vector1.push_back(result);
    }
    // Here i need to return the full vector1 but how?
    // if i use a for-loop, the return will be out of scope:
    // for(int i = 0; i <= size of vector; i++)
    // {
    //     return vector1[i];
    // }
}

我的.hpp文件:

class Example
{
  private:
    double x, min, max;
  public:
    double function(double min, double max, double x);
};

在此之后,我想将给定间隔的结果存储在.txt文件中,以便用外部软件绘制它。

#include <iostream>
#include <fstream>
#include "header.hpp"

int main()
{
    std::ofstream file1("testplot1-output.txt");
    Example test;
    for(x = 0; x <= size of vector1; x++ ) // i don't get how i can access the vector1 from the .cpp file.
    {
        file1 << x << "\t" << test.function(-5, 5) << std::endl;
    }
    file1.close();
    return 0.;
}

2 个答案:

答案 0 :(得分:3)

如果您想要返回向量,只需执行以下操作:

std::vector<double> Example::function(double min, double max)
{
   std::vector<double> vector1;

   for (double x = min; x <= max; x++) {
      const auto result = x * x - 7;
      vector1.push_back(result);
   }

   return vector1;
}

我已经拿出了第三个参数 - 你从未提供过 - 并用局部变量替换它,因为我认为这是你的意图。成员变量似乎也毫无意义。所以:

class Example
{
  public:
    std::vector<double> function(double min, double max);
};

(另外,请考虑使minmax整数而不是浮点值。)

无论如何,在调用范围内:

Example test;
const auto data = test.function(-5, 5);
for (const auto elm : data) {
    file1 << x << "\t" << elm << std::endl;
}

答案 1 :(得分:0)

您需要将函数的返回类型更改为std::vector,然后return vector1

std::vector<double> function(...){
    ...
    return vector1;
}

之后,您可以遍历main.cpp中返回的向量