如何 return vector c++?

How to return vector c++?

我需要一个想法,它允许我 calculate/store 和 return 给定间隔的数学表达式的值。在这种情况下,例如: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.;
}

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

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

之后,您可以在 main.cpp

中迭代 returned 向量

如果您希望 return 向量,只需这样做:

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 整数而不是 floating-point 值。)

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

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

函数没有到returndouble