Lecture 02
- 在main()之前声明function。
- Default parameters
参数可以设置默认值。
带默认值的参数必须放在参数表的最后。 - Value semantics:In java and C++, when variables (int, double) are passed as parameters, their values are copied.
-Modifying a parameter will affect the variable passed in. - Reference semantics: If you declare a parameter with an & after its type, it will link the functions to the same place in memory.
-Modifying a parameter will affect the variable passed in. 引用必须是有内存的地址,不能引用值。C++只会传递copy,除非引用 - Output parameters: (they don’t have to have values, just providing
space to store the output values.) - Procedural decomp.
- Strings, can be changed.
- Character
Lecture 03
Vectors (list)
#include "vector.h"
- vector (aka list): a collection of elements with 0-based indexes
-like a dynamically-resizing array (Java ArrayList or Python list)
// initialize a vector containing 5 integers
Vector<int> nums {42, 17, -6, 0, 28};
Vector<string> names;
names.add("Stu"); // {"Stu"}
names.add("Marty"); // {"Stu", "Marty"}
names.insert(0, "Ed"); // {"Ed", "Stu", "Marty"}
- Why not arrays?
a) Arrays have fixed size and cannot be easily resized. (no .length field)
b) C++ lets you index out of the array bounds
c) An array does not support many operations that you’d want: inserting/deleting elements into the front/middleback of the array, reversing, sorting the elements, earching for a given value… - Vector insert/remove
v.insert(2, 42); //v[2] = 42
-shift elements right to make room for the new element
v.remove(1)
-shift elements left to cover the space left by the removed element.
Grid
#include "gird.h"
like a 2D array, but more powerful
must specify element type in <> (a template or a type parameter)
//construding a Grid
Grid<int> matrix(3, 4);
matrix[0][0] = 75;
...
//or specify elements in {}
Grid<int> matrix = {
{75, 61, 83, 71},
{94, 89, 98, 100},
{63, 54, 51, 49}
};
Looping over a grid
Row-major order:
1. for loop
2. “for each” loop for (int value : grid)
Column-major order:
1. for loop
Grid as parameter
When a Grid is passed by value, C++ makes a copy of its contents.
-Copying is slow; you should usually pass by reference with &
-If the code won’t modify the grid, also pass it as const
A) int computeSum(const Grid g) {
B) void invert(Grid& matrix) {