C++ parsing argument with char & [duplicate] - c++

This question already has answers here:
What is a lambda expression in C++11?
(10 answers)
Closed 1 year ago.
I saw an snippet CC source such as.
imagecb = [ &, xx, yy, zz] (uint32_t a1, int a2) {
...
}
I did know what is symbol of & in the array
this syntax declare an inline functions with 2 arguments a1, a2, right?

it is not the array, it is a lambda expression. Between [] you pass elements from another scope that you need inside expression. & means to get all elements that you need by reference.
In this specific case, variables xx, yy, zz will be copied, but if let's say this lambda expression uses another variable like for example aa it will be passed by reference.
It is worth mentioning that even if the element is passed by reference to a lambda expression, it cannot be modified (in default). To allow modification you need to use keyword mutable
Little code sample:
int xx=0, yy=0, zz=0;
int aa=1;
auto imagecb = [&, xx, yy, zz](uint32_t a1, int a2) mutable {
cout << aa;
aa++;
return aa;
};
cout << endl<<imagecb(2, 3);

Related

Cross product function gives really small values, c++ [duplicate]

This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
Closed 6 years ago.
I am new to programming and here is a simple question about how passing by reference works. In this program, I am calculating roots of a quadratic equation.
void getCoefficients(double &a, double &b, double &c);
void solveQuadratic(double a, double b, double c, double &x1, double &x2);
void printRoots(double x1, double x2);
void error(string msg);
int main() {
double a,b,c,x1,x2;
getCoefficients(a,b,c);
solveQuadratic(a,b,c,x1,x2);
printRoots(x1,x2);
return 0;
}
So, my question is I seem to be passing values to getCoefficients and solveQuadratic from main program but in the function definitions of getCoefficients and solveQuadratic, I seem to be accepting references as arguments and am confused as to how this works?
When passing a variable by reference, whatever changes you make to it in the function are reflected back in the calling function.
On the other hand, when you pass a variable by value, the changes made to it are local, and hence not reflected in the calling function.
For example,
#include "iostream"
using namespace std;
void function1(int &x, int y) // x passed by reference
{
x+=y;
}
void function2(int x, int y) // x passed by value
{
x+=y;
}
int main()
{
int x=10;
function1(x, 10); // x is passed by reference (no & while calling)
cout << x << endl; // 20
function2(x, 1000);// x is passed by value
cout << x << endl; // 20
}
Notice that whatever value of y you pass in the call to function2 does not make any difference to the second cout statement.
You do not decide whether to pass values or references in main. The function definition decides that for you. Irrespective of pass by value or pass by reference, the format of calling a function remains the same.
void getCoefficients(double &a, double &b, double &c);
This says, "I take 3 parameters - all of the type double & (reference to a double). Reference is quite a lot confused with pointers, so I recommend you read this up first.
Let's call the a,b,c inside the main as main_method_vars.
When you call getCoefficients, whatever this function does to the passed variables inside it, is reflected on the main_method_vars. Actually, this method works with the main_method_vars.
If instead you have void getCoefficients(double a, double b, double c), this means that whenever you call this method with the main_method_vars, this method will copy the values of a,b,c and work with new copies, instead of working with the original passed copies to it.
void getCoefficients(double &a, double &b, double &c);
void solveQuadratic(double a, double b, double c, double &x1, double &x2);
For example, function getCoefficients, variable a,b,c is passed by reference, so the value for the three variables will be changed in the main function also, if their value changed in the getCoefficients function.
Although not directly an answer, you could look at the topic "variable scope". It would explain why the symbols "a", "b" and "c" may or may not not represent the same thing in the different functions. The concept of local variables is a prerequisite of understanding of "pass by value", "pass by pointer" and "pass by reference".
You can also do this first test: try changing the names of parameters in one of the functions, for example getCoefficients(double &first,double&second,double &third).
You can also do this second test: try calling solveQuadratic(10, 20, 30, x1,x2) and getCoefficients(1,-2,1). The first should work, but not the second.
Finally, you can try this third test: change the value of arguments x1 and x2 in the printRootsfunction. Then check if these changes also occurred in the main function (after the call to printRoot, of course).

C++ issue with operator overloading with regard to addition [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 5 years ago.
This is my main function:
int main(){
Complex c1(1.0, 5.0);
Complex c2(3.0,-2.0);
Complex c3(1.0, 2.0);
cout << "c1 + c2 + c3 = "
<< c1 + c2 + c3 << endl;
return 0;
}
This is the function I use to add up the required numbers
Complex& operator+(const Complex & x, const Complex & y){
Complex c;
c.a = x.a + y.a;
c.b = x.b + y.b;
return c;
}
a and b are private double variables in my class.
On running my program, I seem to get the output as 1+2i ie(c3) and it only seems to work properly when I add only 2 objects. Is there any way I can tweak my existing code to allow it to work for up-to n terms?
Your operator + returns a reference to the local variable c, which gets destroyed after it is done. Any further use of the result leads to undefined behavior.
You need to return a value, so it gets copied (or a rvalue), but not a reference:
Complex operator+(const Complex & x, const Complex & y)
{...}

Composite function in C++

I am a beginner in C++ and want to do simple example of composite function.
For example, in MATLAB, I can write
a = #(x) 2*x
b = #(y) 3*y
a(b(1))
Answer is 6
I searched following questions.
function composition in C++ / C++11 and
Function Composition in C++
But they are created using advanced features, such as templates, to which I am not much familiar at this time. Is there a simple and more direct way to achieve this? In above MATLAB code, user does not need to know implementation of function handles. User can just use proper syntax to get result. Is there such way in C++?
** Another Edit:**
In above code, I am putting a value at the end. However, if I want to pass the result to a third function, MATLAB can still consider it as a function. But, how to do this in C++?
For example, in addition to above code, consider this code:
c = #(p,q) a(p)* b(q) %This results a function
c(1,2)
answer=12
d = #(r) a(b(r))
d(1)
answer=6
function [ output1 ] = f1( arg1 )
val = 2.0;
output1 = feval(arg1,val)
end
f1(d)
answer = 12
In this code, c takes two functions as input and d is composite function. In the next example, function f1 takes a function as argument and use MATLAB builtin function feval to evaluate the function at val.
How can I achieve this in C++?
How about:
#include <iostream>
int main(int, char**)
{
auto a = [](int x) { return 2 * x; };
auto b = [](int y) { return 3 * y; };
for (int i = 0; i < 5; ++i)
std::cout << i << " -> " << a(b(i)) << std::endl;
return 0;
}
Perhaps I'm misunderstanding your question, but it sounds easy:
int a(const int x) { return x * 2; }
int b(const int y) { return y * 3; }
std::cout << a(b(1)) << std::endl;
Regarding your latest edit, you can make a function return a result of another function:
int fun1(const int c) { return a(c); }
std::cout << fun1(1) << std::endl;
Note that this returns a number, the result of calling a, not the function a itself. Sure, you can return a pointer to that function, but then the syntax would be different: you'd have to write something like fun1()(1), which is rather ugly and complicated.
C++'s evaluation strategy for function arguments is always "eager" and usually "by value". The short version of what that means is, a composed function call sequence such as
x = a(b(c(1)));
is exactly the same as
{
auto t0 = c(1);
auto t1 = b(t0);
x = a(t1);
}
(auto t0 means "give t0 whatever type is most appropriate"; it is a relatively new feature and may not work in your C++ compiler. The curly braces indicate that the temporary variables t0 and t1 are destroyed after the assignment to x.)
I bring this up because you keep talking about functions "taking functions as input". There are programming languages, such as R, where writing a(b(1)) would pass the expression b(1) to a, and only actually call b when a asked for the expression to be evaluated. I thought MATLAB was not like that, but I could be wrong. Regardless, C++ is definitely not like that. In C++, a(b(1)) first evaluates b(1) and then passes the result of that evaluation to a; a has no way of finding out that the result came from a call to b. The only case in C++ that is correctly described as "a function taking another function as input" would correspond to your example using feval.
Now: The most direct translation of the MATLAB code you've shown is
#include <stdio.h>
static double a(double x) { return 2*x; }
static double b(double y) { return 3*y; }
static double c(double p, double q) { return a(p) * b(q); }
static double d(double r) { return a(b(r)); }
static double f1(double (*arg1)(double))
{ return arg1(2.0); }
int main()
{
printf("%g\n", a(b(1))); // prints 6
printf("%g\n", c(1,2)); // prints 12
printf("%g\n", d(1)); // prints 6
printf("%g\n", f1(d)); // prints 12
printf("%g\n", f1(a)); // prints 4
return 0;
}
(C++ has no need for explicit syntax like feval, because the typed parameter declaration, double (*arg1)(double) tells the compiler that arg1(2.0) is valid. In older code you may see (*arg1)(2.0) but that's not required, and I think it makes the code less readable.)
(I have used printf in this code, instead of C++'s iostreams, partly because I personally think printf is much more ergonomic than iostreams, and partly because that makes this program also a valid C program with the same semantics. That may be useful, for instance, if the reason you are learning C++ is because you want to write MATLAB extensions, which, the last time I checked, was actually easier if you stuck to plain C.)
There are significant differences; for instance, the MATLAB functions accept vectors, whereas these C++ functions only take single values; if I'd wanted b to call c I would have had to swap them or write a "forward declaration" of c above b; and in C++, (with a few exceptions that you don't need to worry about right now,) all your code has to be inside one function or another. Learning these differences is part of learning C++, but you don't need to confuse yourself with templates and lambdas and classes and so on just yet. Stick to free functions with fixed type signatures at first.
Finally, I would be remiss if I didn't mention that in
static double c(double p, double q) { return a(p) * b(q); }
the calls to a and b might happen in either order. There is talk of changing this but it has not happened yet.
int a(const int x){return x * 2;}
int b(const int x){return x * 3;}
int fun1(const int x){return a(x);}
std::cout << fun1(1) << std::endl; //returns 2
This is basic compile-time composition. If you wanted runtime composition, things get a tad more involved.

C++ passing by reference or by value? [duplicate]

This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
Closed 6 years ago.
I am new to programming and here is a simple question about how passing by reference works. In this program, I am calculating roots of a quadratic equation.
void getCoefficients(double &a, double &b, double &c);
void solveQuadratic(double a, double b, double c, double &x1, double &x2);
void printRoots(double x1, double x2);
void error(string msg);
int main() {
double a,b,c,x1,x2;
getCoefficients(a,b,c);
solveQuadratic(a,b,c,x1,x2);
printRoots(x1,x2);
return 0;
}
So, my question is I seem to be passing values to getCoefficients and solveQuadratic from main program but in the function definitions of getCoefficients and solveQuadratic, I seem to be accepting references as arguments and am confused as to how this works?
When passing a variable by reference, whatever changes you make to it in the function are reflected back in the calling function.
On the other hand, when you pass a variable by value, the changes made to it are local, and hence not reflected in the calling function.
For example,
#include "iostream"
using namespace std;
void function1(int &x, int y) // x passed by reference
{
x+=y;
}
void function2(int x, int y) // x passed by value
{
x+=y;
}
int main()
{
int x=10;
function1(x, 10); // x is passed by reference (no & while calling)
cout << x << endl; // 20
function2(x, 1000);// x is passed by value
cout << x << endl; // 20
}
Notice that whatever value of y you pass in the call to function2 does not make any difference to the second cout statement.
You do not decide whether to pass values or references in main. The function definition decides that for you. Irrespective of pass by value or pass by reference, the format of calling a function remains the same.
void getCoefficients(double &a, double &b, double &c);
This says, "I take 3 parameters - all of the type double & (reference to a double). Reference is quite a lot confused with pointers, so I recommend you read this up first.
Let's call the a,b,c inside the main as main_method_vars.
When you call getCoefficients, whatever this function does to the passed variables inside it, is reflected on the main_method_vars. Actually, this method works with the main_method_vars.
If instead you have void getCoefficients(double a, double b, double c), this means that whenever you call this method with the main_method_vars, this method will copy the values of a,b,c and work with new copies, instead of working with the original passed copies to it.
void getCoefficients(double &a, double &b, double &c);
void solveQuadratic(double a, double b, double c, double &x1, double &x2);
For example, function getCoefficients, variable a,b,c is passed by reference, so the value for the three variables will be changed in the main function also, if their value changed in the getCoefficients function.
Although not directly an answer, you could look at the topic "variable scope". It would explain why the symbols "a", "b" and "c" may or may not not represent the same thing in the different functions. The concept of local variables is a prerequisite of understanding of "pass by value", "pass by pointer" and "pass by reference".
You can also do this first test: try changing the names of parameters in one of the functions, for example getCoefficients(double &first,double&second,double &third).
You can also do this second test: try calling solveQuadratic(10, 20, 30, x1,x2) and getCoefficients(1,-2,1). The first should work, but not the second.
Finally, you can try this third test: change the value of arguments x1 and x2 in the printRootsfunction. Then check if these changes also occurred in the main function (after the call to printRoot, of course).

putting a '&' after the type [duplicate]

This question already has answers here:
ampersand (&) at the end of variable etc
(5 answers)
Closed 3 years ago.
I am fairly new to programming. I am just moving on to C++ from C in my college courses, and I encountered something that I haven't seen before in C. Sometimes after the type, either in a function declaration or passing a parameter, a & immediately follows the type. For example, we use a struct called Customer in one of our projects, and some of the functions pass Customer&. Why is the ampersand after the type, as opposed to in front? Thanks!
References in C++ simply allow for a cleaner way to execute the following code:
int x = 16;
int* y = &x;
cout << *y;
Which could be written instead as
int x = 16;
int& y = x;
cout << y;
When defining functions, a reference allows a function to change the value of parameters without causing the user of the function to put an ampersand before everything. E.g.
void func( int& a )
{
a = 5;
}
void main()
{
int A = 10;
func( A );
cout << A; // Will output '5'
}
Be careful with this type of mutation, as a programmer using functions like this without checking the implementation might not realize that the function is changing the value of the parameters unless the intent is obvious. init_server(my_server) would be an example of a case where it's obvious, but to_json(my_struct) would clearly be an example where you should not be using a reference to change the struct in any way.
But, one of the most important uses of references, would be function like
int sum_vector( const vector<int>& a ) {
int sum = 0;
for( int i = 0; i < a.size(); i++ ) {
sum += a[i];
}
return sum;
}
If you tried to make sum_vector take in a vector, and you passed in a vector with 100 million entries, then it would have to copy them all over, taking forever. You could take in a pointer, but then the internal parts of the function would have to constantly dereference, and it must called with sum_vector(&myvec), which is more annoying than sum_vector(myvec). In this way, using a const reference, you can prevent the highly inefficient copying of the whole vector into the function body, while keeping syntax neat. Using const lets you reassure yourself that you're not going to change the vector that you were given. And, it also assures the user of your function that you won't change it. Similarly, void to_json(const some_struct&) would be a better function definition as it ensures you won't change the user's data.