I need an idea which allows me to calculate/store and return the value of mathematical expressions for a given interval. In this case for example: x^2 - 7 from -5 to 5
:
My .cpp
file:
#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];
// }
}
my .hpp
file:
class Example
{
private:
double x, min, max;
public:
double function(double min, double max, double x);
};
After this i would like to store the result for the given interval in a .txt
file to plot it with the external software.
#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.;
}
If you wish to return the vector, simply do so:
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;
}
I have taken out that third argument — which you never provided — and replaced it with a local variable, as I believe that was your intention. The member variables also seem to be pointless. So:
class Example
{
public:
std::vector<double> function(double min, double max);
};
(Also, consider making min
and max
integers rather than floating-point values.)
Anyway, then, in the calling scope:
Example test;
const auto data = test.function(-5, 5);
for (const auto elm : data) {
file1 << x << "\t" << elm << std::endl;
}
Functions don't have to return double
.
You need to change the return type of your function to std::vector
and then return vector1
std::vector<double> function(...){
...
return vector1;
}
after that you can iterate over the returned vector in your main.cpp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.