Академический Документы
Профессиональный Документы
Культура Документы
Organizing Computations
C++ offers two ways of organizing your computations: functions and data
structures. Ultimately these can both be combined into a class. We can
start with some information from the first example of Chapter 4 of Accelerated C++ Programming.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//
//
//
//
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
We define the type vec sz because they are local and we dont want it
to conflict outside this. We dont know who is going to be running our
program, so what we can do is throw an exception if the vector is empty.
When a program throws an exception, execution stops in the part of the
program in which the throw appears, and passes to another part of the
program, along with an exception object. Another point is that because
we are passing by value, we are taking a copy of the original vec vector.
This is important because the sort function changes the values of its input.
Taking the median of a vector should not change the vector itself.
We can combine this grading into a function itself
1
2
3
4
5
6
7
8
9
1.0.1
There is no direct way to return more than one value from a function, but
you can give the function a reference to an object so it can directly modify
it. This is common for functions that read in inputs.
We have a reference to in and hw so we can modify them! This reference is something that we are not going to copy because it is an lvalue.
Since in the function read hw, we are returning the stream, we can use it
as the argument to an if statement.
Note on clear()
This member function works for both vectors and istream objects. However the function works fundamentally different for both objects. For a
vector, the function clears out the vector for future use. For the istream
object, clear() moves the object out a an error state.
1.0.2
Data structures
A convenient type that can hold information of many different things into
one object is called a structure.
1.1
Chapter 5 in AC++