Function, Reference, and Struct
Function:
In C++, we can define some functions ourself with a return type and parameters(or no parameters).
let's focus on the function's declaration:int sum(int a, int b)
'int' indicates that the return type of the function is an integer. (int a, int b)
tells us that there are two parametersa
and b
with the type of int
1 2 3 4 5 6 7 8 9 |
|
Functions can also have many kinds of return type
such as bool
, void
, double
and so on.
Using the return type bool
, we can write some conditioning function.
1 2 3 4 5 6 7 8 9 10 |
|
Reference
In previous examples, if we modify the formal parameter inside function, the actual parameter outside the function are not modified.
Thus, if we want to modify the actual parameter(the real parameter we use when calling the function) inside the function, we can use &
to make a reference.
1 2 3 4 5 6 7 8 9 10 11 |
|
Struct
When we want to store multiple data in one variable, we can create a struct to achieve this goal.
In a struct, we can have multiple variables and even functions built in it, but we don't often do it in competitive programming.(from my personal perspective)
After declaring this struct, we can use it as a variable type and declare variables using struct's name:point p1;
just like how we define an integerint p2;
1 2 3 4 5 6 7 8 9 |
|
Struct may not seem powerful at first, but it is useful when we are dealing with situations that each single element has multiple attributes.(such as some graph algorithms)
Practice Problems:
to be completed.