storing values in array whenever the function is being called - c++

I am new to c++. I have to calculate a value via equation and store that value each time whenever the function is being called. I have created an array of size 10 and calculated myValue then tried to store that value. Is this right way to do so? Will it work in way that each time whenever the function is called it will calculate and store myValue and use that value n[i-1] in the next call to calculate my value n[i]. Let's say in 1st call myvalue is 0.5. In next call it would be myValue = (1-0.3)* 0.5. Will it store all 10 values in 10 calls and use the last stored value to calculate myValue. It is not showing me any error when I am compiling it but still I have doubt.
static double
CalculatemyValue(Node* ch)
{
float gamma=0.3;
double myValue = 0.0;
int n[10];
int i = 0;
n[i] = myValue;
myValue = ((1-gamma)*n[i-1]) //previous value
return myValue;
}

In the given code
static double
CalculatemyValue(Node* ch)
{
float gamma=0.3;
double myValue = 0.0;
int n[10];
int i = 0;
n[i] = myValue;
myValue = ((1-gamma)*n[i-1]) //previous value
return myValue;
}
… the array n is a local automatic variable. It's created anew each time execution reaches the declaration, and destroyed when execution leaves the block. No information is retained between calls.
One good way to retain state between calls is to make the function a member function of a class, whose data members constitute the state you want to keep, e.g. like this:
class Power_sequence
{
private:
double gamma_;
double value_;
public:
auto gamma() const -> double { return gamma_; }
void advance() { value_ *= 1 - gamma_; }
auto current() const -> double { return value_; }
auto next()
-> double
{
double const result = current();
advance();
return result;
}
Power_sequence( double const gamma = 0.3 )
: gamma_( gamma )
, value_( 1.0 )
{}
};
… which you would use like this:
Power_sequence seq;
for( int i = 1; i <= 42; ++i )
{
cout << seq.next() << endl;
}
Disclaimer: above code not checked by a compiler.
Another way is to pass the state as an explicit argument to the function.

Related

Idiom for data aggregation and post processing in C++

A common task in programming is to process data on the fly and, when all data are collected, do some post processing. A simple example for this would be the computation of the average (and other statistics), where you can have a class like this
class Statistic {
public:
Statistic() : nr(0), sum(0.0), avg(0.0) {}
void add(double x) { sum += x; ++nr; }
void process() { avg = sum / nr; }
private:
int nr;
double sum;
double avg;
};
A disadvantage with this approach is, that we always have to remember to call the process() function after adding all the data. Since in C++ we have things like RAII, this seems like a less than ideal solution.
In Ruby, for example, we can write code like this
class Avg
attr_reader :avg
def initialize
#nr = 0
#sum = 0.0
#avg = nil
if block_given?
yield self
process
end
end
def add(x)
#nr += 1
#sum += x.to_f
end
def process
#avg = #sum / #nr
end
end
which we then can call like this
avg = Avg.new do |a|
data.each {|x| a.add(x)}
end
and the process method is automatically called when exiting the block.
Is there an idiom in C++ that can provide something similar?
For clarification: this question is not about computing the average. It is about the following pattern: feeding data to an object and then, when all the data is fed, triggering a processing step. I am interested in context-based ways to automatically trigger the processing step - or reasons why this would not be a good idea in C++.
"Idiomatic average"
I don't know Ruby but you can't translate idioms directly anyhow. I know that calculating the average is just an example, so lets see what we can get from that example...
Idiomatic way to caclulate sum, and average of elements in a container is std::accumulate:
std::vector<double> data;
// ... fill data ...
auto sum = std::accumulate( a.begin(), a.end() , 0.0);
auto avg = sum / a.size();
The building blocks are container, iterator and algorithms.
If you do not have elements to be processed readily available in a container you can still use the same algorithms, because algorithms only care about iterators. Writing your own iterators requires a bit of boilerplate. The following is just a toy example that calcualtes average of results of calling the same function a certain number of times:
#include <numeric>
template <typename F>
struct my_iter {
F f;
size_t count;
my_iter(size_t count, F f) : count(count),f(f) {}
my_iter& operator++() {
--count;
return *this;
}
auto operator*() { return f(); }
bool operator==(const my_iter& other) const { return count == other.count;}
};
int main()
{
auto f = [](){return 1.;};
auto begin = my_iter{5,f};
auto end = my_iter{0,f};
auto sum = std::accumulate( begin, end, 0.0);
auto avg = sum / 5;
std::cout << sum << " " << avg;
}
Output is:
5 1
Suppose you have a vector of paramters for a function to be called, then calling std::accumulate is straight-forward:
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
auto f = [](int x){return x;};
std::vector<int> v = {1,2,5,10};
auto sum = std::accumulate( v.begin(), v.end(), 0.0, [f](int accu,int add) {
return accu + f(add);
});
auto avg = sum / 5;
std::cout << sum << " " << avg;
}
The last argument to std::accumulate specifies how the elements are added up. Instead of adding them up directly I add up the result of calling the function. Output is:
18 3.6
For your actual question
Taking your question more literally and to answer also the RAII part, here is one way you can make use of RAII with your statistic class:
struct StatisticCollector {
private:
Statistic& s;
public:
StatisticCollector(Statistic& s) : s(s) {}
~StatisticCollector() { s.process(); }
};
int main()
{
Statistic stat;
{
StatisticCollector sc{stat};
//for (...)
// stat.add( x );
} // <- destructor is called here
}
PS: Last but not least there is the alternative to just keep it simple. Your class definition is kinda broken, because all results are private. Once you fix that, it is kinda obvious that you need no RAII to make sure process gets called:
class Statistic {
public:
Statistic() : nr(0), sum(0.0), avg(0.0) {}
void add(double x) { sum += x; ++nr; }
double process() { return sum / nr; }
private:
int nr;
double sum;
};
This is the right interface in my opinion. The user cannot forget to call process because to get the result they need to call it. If the only purpose of the class is to accumulate numbers and process the result it should not encapsulate the result. The result is for the user of the class to store.

using the return value of one function as an argument in another function in c++

I found some related answers but couldn't understand it clearly because the codes were complicated for me.
In this program I used the dif () to find the difference in price then stored the return value total in variable difrnc. Then I used the difrnc variable as an argument for the function call
inflation=inflan(difrnc,lyp) //(calculates the inflation)
Instead of storing the total in variable difrnc can I directly use the answer from the function dif() as an argument for the function inflan() in its definition and how?
Sorry if it is a repeated question it would be great if someone could explain it using this program.
#include<iostream>
using namespace std;
double dif(double lp,double cp);//cp= current price,lp= last price, current
double inflan(double difference,double lastyp);
double cost(double cp,double inrate);
int main()
{
double lyp,cyp,difrnc,inflation,one_year_cost; // lyp = last year price,cyp=current year price,
for(int i=0;i>=0;i++)
{
cout<<"Enter current years price :";
cin>>cyp;
cout<<"Enter last Years price: ";
cin>>lyp;
difrnc=dif(lyp,cyp);
if(difrnc<0)
{
cout<<"price decreased by "<<difrnc<<endl;
}
else
{
cout<<"price increased by "<<difrnc<<endl;
}
inflation=inflan(difrnc,lyp);
one_year_cost=cost(cyp,inflation);
cout<<one_year_cost<<endl;
}
}
// to find the difference in price
double dif(double lp,double cp)
{
double total;
total=cp-lp;
return(total);
}
// to find the inflation
double inflan(double difference,double lastyp)
{
double inrate;
inrate=difference/lastyp;
return(inrate);
}
// to find estimated cost in one year
double cost(double cp,double inrate)
{
double
totalc=cp+inrate;
return(totalc);
}
Yes you can like this inflatio n = inflan(dif(lyp,cyp),lyp);
However, since you use the function returned value more than once, it make more sense to keep it as it is.
Aside from your current issue in your functions you can simplify them by removing their local variables and just simply return the evaluated expression.
For Example: You have this ->
double cost( double cp, double inrate ) {
double totalc = cp + inrate;
return totalc;
}
It is safe and efficient to do this instead:
double cost( double cp, double inrate ) {
return cp + inrate;
}
You can do that for any simple function that doesn't go through any loops.
As for your actual issue check out this quick program;
Sample.cpp
#include <iostream>
int five() {
return 5;
}
int ten() {
return 10;
}
int add( int a, int b ) {
return a + b;
}
int main() {
std::cout << add( five(), ten() ) << std::endl;
return 0;
}
Set a break point within the first line of your main function and step through the code line by line while examining your stack calls as well as your local and auto variables to see what is happening on each line of your functions to see the values that are being assigned to each variable.

Get return of a function without sending anything

I have a function header:
double countThis(double counter);
Then, in my main I do this:
double test = 10;
countThis(test);
Then comes the function:
double countThis(double counter) {
double counted = counter;
return counted;
}
On the bottom, I have one last function, and here I want to get double counted without having to do countThis(something), I just want to get the return from the previous call that was made in main and get the value 10 (counted).
One way to achieve this sort of persistence is to use a class and define an instance of that class:
struct Counter
{
double counted;
double countThis(double counter)
{
return counted = counter; // assign counter to counted, and return that value.
}
};
At the point of use:
int main()
{
Counter c;
c.countThis(10);
// c.counted contains the last value sent to countThis, in this case, 10
}
The instance c is used to persist the value that you pass to countThis.
Do this:
double test = 10;
double ret;
ret = countThis(test);
// Now the value returned by countThis is in ret
You can use global variable.(double counted) and in the function
double countThis(double counter) {
counted = counter;
return counted;
}
define another function to just return counted
double count() {
return counted;
}
But,i suggest you to create a struct and make getter and setter on it.
Why not just copy the value into a new instance of double?
Example:
double test = 10;
countThis(test);
double something = test;

Trying to understand lambdas

Trying to understand lambdas in C++, what I do not understand is this:
int multiplier = 5;
auto timesFive = [multiplier](int a) { return a * multiplier; };
std::cout << timesFive(2) << '\n'; // Prints 10
multiplier = 15;
std::cout << timesFive(2) << '\n'; // Still prints 2*5 == 10 (???) - Should it be 30?
When the program calls the timesFive() the second time, I expect the result to be 30. But why is the result Still prints 2*5 == 10, not prints 2*15 == 30? Perhaps the lambda function somehow cannot track the value of multiplier, even though we have already tried to capture it?
And what is the way to get the desired result?
You captured multiplier by value, which means it was copied into the lambda. You need to capture it by reference:
int multiplier = 5;
auto timesFive = [&multiplier](int a) { return a * multiplier; };
std::cout << timesFive(2);
multiplier = 15;
std::cout << timesFive(2);
Lambdas are syntatic sugar for an unnamable class and the instance thereof. Sometimes expanding your code out to what this unnamable class can help understanding what is going on.
[ capture_list ]( arg_list ) -> return_value_clause_opt { body };
becomes very roughly (pseudo-code):
struct anonymous_type {
capture_list;
auto operator()( arg_list ) const -> return_value_clause_opt {
body
}
anonymous_type( capture_list_in ):capture_list(capture_list_in) {}
};
If you list a variable in capture_list by its plain name, it is copied into a copy within the anonymous class.
So your timesFive became
struct __secret_name__ {
int multiplier;
int operator()(int a) const { return a*multiplier; }
};
int multiplier = 5;
auto timesFive = __secret_name__{multiplier};
It should be pretty clear that changing multiplier in the above code won't change the behavior of timesFive.
If you put a & in front of the name, a non-const reference is placed within the anonymous class.
struct __secret_name__ {
int& multiplier;
int operator()(int a) const { return a*multiplier; }
};
int multiplier = 5;
auto timesFive = __secret_name__{multiplier};
now, changing multiplier will change the behavior of timesFive, because timesFive holds a reference to multiplier, not a copy of it.
Some details skipped above for brevity. The name __secret_name__ is only for exposition. The member variables of the lamba are not actually public. The lambda being trivially constructible is implementation defined even if its data is. Etc.

C++ Dynamically Define Function

I am on visual c++ working on a console calculator, I am creating a way to let the user define a custom linear function. Here is where I am stumped: Once I get the users desired name of the function, the slope, and the y-intercept, I need to use that data to create a callable function that I can pass to muParser.
In muParser, you define custom functions like this:
double func(double x)
{
return 5*x + 7; // return m*x + b;
}
MyParser.DefineFun("f", func);
MyParser.SetExpr("f(9.5) - pi");
double dResult = MyParser.Eval();
How could I dynamically create a function like this based on the users input for the values 'm' and 'b' and pass that to the 'DefineFun()' method?
This is what I have so far:
void cb_SetFunc(void)
{
string FuncName, sM, sB;
double dM, dB;
bool GettingName = true;
bool GettingM = true;
bool GettingB = true;
regex NumPattern("[+-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?");
EchoLn(">>> First, enter the functions name. (Enter 'cancel' to abort)");
EchoLn(">>> Only letters, numbers, and underscores can be used.");
try
{
do // Get the function name
{
Echo(">>> Enter name: ");
FuncName = GetLn();
if (UserCanceled(FuncName)) return;
if (!ValidVarName(FuncName))
{
EchoLn(">>> Please only use letters, numbers, and underscores.");
continue;
}
GettingName = false;
} while (GettingName);
do // Get the function slope
{
Echo(">>> Enter slope (m): ");
sM = GetLn();
if (UserCanceled(sM)) return;
if (!regex_match(sM, NumPattern))
{
EchoLn(">>> Please enter any constant number.");
continue;
}
dM = atof(sM.c_str());
GettingM = false;
} while (GettingM);
do // Get the function y-intercept
{
Echo(">>> Enter y-intercept (b): ");
sB = GetLn();
if (UserCanceled(sB)) return;
if (!regex_match(sB, NumPattern))
{
EchoLn(">>> Please enter any constant number.");
continue;
}
dB = atof(sB.c_str());
GettingB = false;
} while (GettingB);
// ------------
// TODO: Create function from dM (slope) and
// dB (y-intercept) and pass to 'DefineFun()'
// ------------
}
catch (...)
{
ErrMsg("An unexpected error occured while trying to set the function.");
}
}
I was thinking that there isn't a way to define an individual method for each user-defined-function. Would I need to make a vector<pair<double, double>> FuncArgs; to keep track of the appropriate slopes and y-intercepts then call them dynamically from the function? How would I specify which pair to use when I pass it to DefineFun(FuncStrName, FuncMethod)?
What you need (in addition to a script language interpreter) is called a "trampoline". There is no standard solution to create those, in particular since it involves creating code at runtime.
Of course, if you accept a fixed number of trampolines, you can create them at compile time. And if they're all linear, this might be even easier:
const int N = 20; // Arbitrary
int m[N] = { 0 };
int b[N] = { 0 };
template<int I> double f(double x) { return m[I] * x + b; }
This defines a set of 20 functions f<0>...f<19> which use m[0]...m[19] respectively.
Edit:
// Helper class template to instantiate all trampoline functions.
double (*fptr_array[N])(double) = { 0 };
template<int I> struct init_fptr<int I> {
static const double (*fptr)(double) = fptr_array[I] = &f<I>;
typedef init_fptr<I-1> recurse;
};
template<> struct init_fptr<-1> { };
I would keep it simple:
#include <functional>
std::function<double(double)> f; // this is your dynamic function
int slope, yintercept; // populate from user input
f = [=](double x) -> double { return slope * x + yintercept; };
Now you can pass the object f to your parser, which can then call f(x) at its own leisure. The function object packages the captured values of slope and yintercept.
GiNaC is C++ lib which can parse and evaluate math expressions.
Generating a fixed array of functions bindable to boost function.
Someone else already said about a similar method, but since I'd taken the time to write the code, here it is anyway.
#include <boost/function.hpp>
enum {
MAX_FUNC_SLOTS = 255
};
struct FuncSlot
{
double (*f_)(double);
boost::function<double(double)> closure_;
};
FuncSlot s_func_slots_[MAX_FUNC_SLOTS];
template <int Slot>
struct FuncSlotFunc
{
static void init() {
FuncSlotFunc<Slot-1>::init();
s_func_slots_[Slot - 1].f_ = &FuncSlotFunc<Slot>::call;
}
static double call(double v) {
return s_func_slots_[Slot - 1].closure_(v);
}
};
template <> struct FuncSlotFunc<0> {
static void init() {}
};
struct LinearTransform
{
double m_;
double c_;
LinearTransform(double m, double c)
: m_(m)
, c_(c)
{}
double operator()(double v) const {
return (v * m_) + c_;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
FuncSlotFunc<MAX_FUNC_SLOTS>::init();
s_func_slots_[0].closure_ = LinearTransform(1, 0);
s_func_slots_[1].closure_ = LinearTransform(5, 1);
std::cout << s_func_slots_[0].f_(1.0) << std::endl; // should print 1
std::cout << s_func_slots_[1].f_(1.0) << std::endl; // should print 6
system("pause");
return 0;
}
So, you can get the function pointer with: s_func_slots_[xxx].f_
And set your action with s_func_slots_[xxx].closure_
Try to embed to your application some script language. Years ago I was using Tcl for similar purpose - but I do not know what is the current time best choice.
Either you can start from Tcl or search yourself for something better:
See: Adding Tcl/Tk to a C application