├── .gitignore ├── README.md ├── appendix-optimization └── Appendix1-code-optimization.pptx ├── projects ├── 2021Fall │ ├── Project5-goodexamples-2021fall-by何泽安.pdf │ ├── Project5-goodexamples-2021fall-by廖铭骞.pdf │ ├── project1.md │ ├── project2.md │ ├── project3.md │ ├── project4-good-example-2021fall-by何泽安.pdf │ ├── project4-good-example-2021fall-by徐临风.pdf │ ├── project4-good-example-2021fall-by董正.pdf │ ├── project4.md │ ├── project5-introduction.pptx │ └── project5.md ├── 2022Fall │ ├── project1.md │ ├── project2.md │ ├── project3.md │ ├── project4.md │ └── project5.md ├── 2023Spring │ ├── Project5.md │ ├── project1.md │ ├── project2.md │ ├── project3.md │ └── project4.md ├── 2024Spring │ ├── project1.md │ ├── project2.md │ ├── project3.md │ ├── project4.md │ └── project5.md └── 2025Spring │ ├── project1.md │ ├── project2.md │ ├── project3.md │ └── project4.md ├── rust ├── Rust-Lab1.pdf ├── Rust-Lab1.pptx ├── Rust-Lab2.pdf ├── Rust-Lab2.pptx ├── Rust-Lecture1.pdf ├── Rust-Lecture1.pptx ├── Rust-Lecture2.pdf ├── Rust-Lecture2.pptx └── hello │ ├── Cargo.toml │ └── src │ └── main.rs ├── week01 ├── Lab01.pdf ├── Lab01.pptx ├── Lecture01.pdf ├── Lecture01.pptx ├── README.md └── examples │ ├── argument.cpp │ ├── hello.cpp │ ├── lab │ ├── add.cpp │ ├── add.h │ └── main.cpp │ ├── macro.cpp │ ├── main.cpp │ ├── mainmul.cpp │ ├── mul.cpp │ └── mul.hpp ├── week02 ├── Lab02.pdf ├── Lab02.pptx ├── Lecture02.pdf ├── Lecture02.pptx ├── README.md ├── examples │ ├── bool.cpp │ ├── char.cpp │ ├── conversion.cpp │ ├── float.cpp │ ├── init.cpp │ ├── intmax.cpp │ ├── nan.cpp │ ├── overflow.cpp │ ├── precision.cpp │ └── size.cpp └── images │ ├── float_format.svg │ └── integer-sign-bit.png ├── week03 ├── Lab03.pdf ├── Lab03.pptx ├── Lecture03.pdf ├── Lecture03.pptx ├── README.md └── examples │ ├── for.cpp │ ├── goto.cpp │ ├── if.cpp │ ├── lab │ ├── Makefile │ ├── factorial.cpp │ ├── functions.h │ ├── main.cpp │ └── printhello.cpp │ ├── switch.cpp │ ├── ternary.cpp │ └── while.cpp ├── week04 ├── Lab04.pdf ├── Lab04.pptx ├── Lecture04.pdf ├── Lecture04.pptx ├── README.md ├── array-illustration.xlsx └── examples │ ├── array.cpp │ ├── cmakedemo │ ├── CMakeLists.txt │ └── main.cpp │ ├── const-array.cpp │ ├── enum.cpp │ ├── index-bound.cpp │ ├── initchar.cpp │ ├── lab │ ├── CMakeLists.txt │ ├── factorial.cpp │ ├── functions.h │ ├── main.cpp │ └── printhello.cpp │ ├── md-array.cpp │ ├── stdstring.cpp │ ├── stringelement.cpp │ ├── stringop.cpp │ ├── struct.c │ ├── structpadding.cpp │ ├── typedef.cpp │ ├── union.cpp │ ├── unknow-size-array.cpp │ └── variable-array.cpp ├── week05 ├── Lab05.pdf ├── Lab05.pptx ├── Lecture05.pdf ├── Lecture05.pptx ├── README.md ├── examples │ ├── arithmetic.cpp │ ├── bound.cpp │ ├── const-pointer.cpp │ ├── memoryleak.c │ ├── newdelete.cpp │ ├── pointer-array.cpp │ ├── pointer-convert.cpp │ ├── pointer-pointer.cpp │ ├── pointer-struct.cpp │ ├── pointer.cpp │ └── stack-heap.cpp └── images │ ├── data-segments.png │ ├── pointer-arithmetic.png │ ├── pointer-array-elements.png │ ├── pointer-pointer.png │ ├── pointer-struct.png │ └── pointer.png ├── week06 ├── Lab06.pdf ├── Lab06.pptx ├── Lecture06.pdf ├── Lecture06.pptx ├── README.md └── examples │ ├── function.cpp │ ├── inline.cpp │ ├── lab │ ├── main.cpp │ ├── mymath.cpp │ └── mymath.h │ ├── nofunction.cpp │ ├── param-pointer.cpp │ ├── param-reference.cpp │ └── reference.cpp ├── week07 ├── Lab07.pdf ├── Lab07.pptx ├── Lecture07.pdf ├── Lecture07.pptx ├── README.md └── examples │ ├── default-argument.cpp │ ├── function-pointer.cpp │ ├── function-reference.cpp │ ├── lab │ ├── main.cpp │ ├── mymath.cpp │ └── mymath.h │ ├── overload.cpp │ ├── recursion.cpp │ ├── specialization.cpp │ ├── template1.cpp │ └── template2.cpp ├── week08 ├── Lab08.pdf ├── Lab08.pptx ├── Lecture08-cuda.pptx ├── Lecture08.pdf ├── Lecture08.pptx ├── README.md └── examples │ ├── CMakeLists.txt │ ├── cuda │ ├── arrayadd.cu │ ├── hellocuda.cu │ └── matadd.cu │ ├── lab-python │ ├── demo1.py │ ├── demo2.py │ ├── demo3.py │ ├── demo4.py │ └── fibs.py │ ├── main.cpp │ ├── matoperation.cpp │ └── matoperation.hpp ├── week09 ├── Lab09.pdf ├── Lab09.pptx ├── Lecture09.pdf ├── Lecture09.pptx ├── README.md └── examples │ ├── access-attribute.cpp │ ├── array.cpp │ ├── const.cpp │ ├── constructor.cpp │ ├── destructor.cpp │ ├── firstclass.cpp │ ├── function.cpp │ ├── multi-files │ ├── CMakeLists.txt │ ├── main.cpp │ ├── student.cpp │ └── student.hpp │ ├── static.cpp │ └── this.cpp ├── week10 ├── Lab10.pdf ├── Lab10.pptx ├── Lecture10.pdf ├── Lecture10.pptx ├── README.md └── examples │ ├── example1 │ ├── main.cpp │ └── time.hpp │ ├── example2 │ ├── main.cpp │ └── time.hpp │ ├── example3 │ ├── main.cpp │ └── time.hpp │ ├── example4 │ ├── main.cpp │ └── time.hpp │ ├── example5 │ ├── main.cpp │ └── time.hpp │ ├── exampleMat │ ├── CMakeLists.txt │ └── matexample.cpp │ └── stringdemo.cpp ├── week11 ├── Lab11.pdf ├── Lab11.pptx ├── Lecture11.pdf ├── Lecture11.pptx ├── README.md └── examples │ ├── example1 │ ├── main.cpp │ └── mystring.hpp │ ├── example2 │ ├── main.cpp │ └── mystring.hpp │ ├── lab │ ├── matrix.h │ └── matrixdemo.cpp │ ├── shared_ptr.cpp │ └── unique_ptr.cpp ├── week12 ├── Lab12.pdf ├── Lab12.pptx ├── Lecture12.pdf ├── Lecture12.pptx ├── README.md └── examples │ ├── derive.cpp │ ├── derived-memory │ └── mystring.hpp │ ├── lab12 │ ├── demo0.cpp │ ├── demo1.cpp │ ├── demo2.cpp │ ├── demo3.cpp │ ├── duck_type.py │ ├── employee_demo1.cpp │ ├── employee_destructor1.cpp │ ├── employee_destructor2.cpp │ ├── p_c_demo3.cpp │ └── p_c_demo3.py │ ├── matrix │ ├── main.c │ ├── matrix.c │ └── matrix.h │ ├── protect.cpp │ └── virtual.cpp ├── week13 ├── Lab13.pdf ├── Lab13.pptx ├── Lecture13.pdf ├── Lecture13.pptx ├── README.md └── examples │ ├── matclass.cpp │ ├── mattemplate.cpp │ ├── nontypeparam.cpp │ └── specialization.cpp ├── week14 ├── Lab14.pdf ├── Lab14.pptx ├── Lecture14.pdf ├── Lecture14.pptx ├── README.md └── examples │ ├── assert.cpp │ ├── derived.cpp │ ├── error1.cpp │ ├── error2.cpp │ ├── error3.cpp │ ├── error4.cpp │ ├── error5.cpp │ ├── nothrow.cpp │ ├── stderr.c │ └── stderr.cpp └── week15 ├── Lab15.pdf ├── Lab15.pptx ├── Lecture15.pdf ├── Lecture15.pptx ├── README.md └── examples ├── const_cast.cpp ├── friend.cpp ├── friend2.cpp ├── nested-enum1.cpp ├── nested-enum2.cpp ├── nestedclass.cpp ├── reinterpret_cast.cpp ├── rtti.cpp └── typeid.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *.out 2 | *.o 3 | ~$* 4 | settings.json 5 | .DS_Store 6 | .vscode 7 | -------------------------------------------------------------------------------- /appendix-optimization/Appendix1-code-optimization.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/appendix-optimization/Appendix1-code-optimization.pptx -------------------------------------------------------------------------------- /projects/2021Fall/Project5-goodexamples-2021fall-by何泽安.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/projects/2021Fall/Project5-goodexamples-2021fall-by何泽安.pdf -------------------------------------------------------------------------------- /projects/2021Fall/Project5-goodexamples-2021fall-by廖铭骞.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/projects/2021Fall/Project5-goodexamples-2021fall-by廖铭骞.pdf -------------------------------------------------------------------------------- /projects/2021Fall/project1.md: -------------------------------------------------------------------------------- 1 | # A Simple Calculator 2 | 3 | Implement a calculator which can multiply two integers. 4 | 5 | ## Requirements 6 | 7 | 1. When you run the program as follows, it will output the expression and the result. 8 | 9 | ```bash 10 | $./mul 11 | Please input two integers 12 | 2 3 13 | 2 * 3 = 6 14 | ``` 15 | 16 | 2. If you input two integers by the command line arguments, it can handle. 17 | 18 | ```bash 19 | $./mul 2 3 20 | 2 * 3 = 6 21 | ``` 22 | 23 | 3. If you input some non-integer numbers, the program can tell you that the input is wrong. 24 | 25 | ```bash 26 | ./mul 27 | Please input two integers 28 | a 2 29 | ``` 30 | 31 | 4. If you input some big integers, what will happen? Please describe some possible solutions, and try to implement them. 32 | 33 | ```bash 34 | ./mul 35 | Please input two integers 36 | 1234567890 1234567890 37 | ``` 38 | 39 | 5. Some others which can improve the program. 40 | 41 | ## Rules: 42 | 43 | 1. Please submit your project report before its deadline. After the deadline (even 1 second), **0 score!** (or students who enroll in this course before Sep. 6, they should submit their project reports by 23:59 on Sep. 19. For the rest students they should submit their project reports in one week or by Sep. 19 (the later one) after they enroll in the course. 44 | 1. Please submit two separated files: report.pdf and source.cpp. Please do **NOT** put the two files into a compressed one. 45 | 1. You score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 46 | 1. Please pay more attention to your code style. After all this is not ACM-ICPC contest. You have enough time to write code with both correct result and good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 47 | -------------------------------------------------------------------------------- /projects/2021Fall/project2.md: -------------------------------------------------------------------------------- 1 | # Project 2: Matrix multiplication 2 | 3 | Please implement a program to multiply two matrices in two files. There are 6 files in the attachment. `mat-A-32.txt` is for matrix A, the matrix size is 32x32. Other files are similar. 4 | 5 | ## Requirements 6 | 7 | 1. When you run the program as follows, it will output the result into an output file such as `out32.txt`. 8 | 9 | ```bash 10 | $./matmul mat-A-32.txt mat-B-32.txt out32.txt 11 | ``` 12 | ```bash 13 | $./matmul mat-A-256.txt mat-B-256.txt out256.txt 14 | ``` 15 | ```bash 16 | $./matmul mat-A-2048.txt mat-B-2048.txt out2048.txt 17 | ``` 18 | 19 | 2. Please implement the matrix multiplication in `float` and `double` separately, and compare the time consumed and the results. Give detailed analysis on the speed and accuracy. 20 | 21 | 3. You can try to improve the speed, and introduce the methods in the report. 22 | 23 | 24 | ## Rules: 25 | 26 | 1. Please submit your project report before its deadline. After the deadline, **23:59 on Sep. 30**, (even 1 second), **0 score!**. 27 | 1. Please submit two separated files: report.pdf and source.cpp. Please do **NOT** put the two files into a compressed one. 28 | 1. You score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 29 | 1. Please pay more attention to your code style. After all this is not ACM-ICPC contest. You have enough time to write code with both correct result and good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 30 | -------------------------------------------------------------------------------- /projects/2021Fall/project3.md: -------------------------------------------------------------------------------- 1 | # Project 3: Matrix Structure and Multiplication in C 2 | 3 | **You can only use C, nor C++, in the project.** The project is an improvement of Project 2, but only `float` matrix structure is needed to implement. 4 | 5 | ## Requirements 6 | 7 | 1. The programming language can only be C, not C++. Please save your source code into `*.c` files, and compile them using a C compiler such as gcc (not g++). Try to use Makefile or CMake to manage your source code. 8 | 9 | 1. Design a `struct` for matrices, and the `struct` should contain the data of a matrix, the number of columns, the number of rows, etc. 10 | 11 | 1. Implement some functions to 12 | * create a matrix 13 | * delete a matrix 14 | * copy a matrix (copy the data from a matrix to another) 15 | * multiply two matrices 16 | * some other functions needed 17 | 18 | 19 | 1. When you run the program as follows, it will output the result into an output file such as `out32.txt`. The data files are the same with those in Project 2. 20 | 21 | ```bash 22 | $./matmul mat-A-32.txt mat-B-32.txt out32.txt 23 | ``` 24 | ```bash 25 | $./matmul mat-A-256.txt mat-B-256.txt out256.txt 26 | ``` 27 | ```bash 28 | $./matmul mat-A-2048.txt mat-B-2048.txt out2048.txt 29 | ``` 30 | 31 | 1. Try to improve the speed of matrix multiplication. Introduce how you improve it in the report. You should explicitly introduce the differences between this one and Project 2. 32 | 33 | 1. Compare the speed of your implementation with OpenBLAS (https://www.openblas.net/). 34 | 35 | ## Rules: 36 | 37 | 1. Please submit your project report before its deadline. After the deadline, **23:59 on Oct. 24**, (even 1 second), **0 score!**. 38 | 1. Please submit the files as: report.pdf, source1.c, source2.c, header.h. I think you do not need more than 5 files for the project. Please do **NOT** put the files into a compressed one. 39 | 1. You score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 40 | 1. Please pay more attention to your code style. After all this is not ACM-ICPC contest. You have enough time to write code with both correct result and good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 41 | -------------------------------------------------------------------------------- /projects/2021Fall/project4-good-example-2021fall-by何泽安.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/projects/2021Fall/project4-good-example-2021fall-by何泽安.pdf -------------------------------------------------------------------------------- /projects/2021Fall/project4-good-example-2021fall-by徐临风.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/projects/2021Fall/project4-good-example-2021fall-by徐临风.pdf -------------------------------------------------------------------------------- /projects/2021Fall/project4-good-example-2021fall-by董正.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/projects/2021Fall/project4-good-example-2021fall-by董正.pdf -------------------------------------------------------------------------------- /projects/2021Fall/project4.md: -------------------------------------------------------------------------------- 1 | # Project 4: A Class for Matrices 2 | 3 | Please use C++ to implement a class. 4 | 5 | ## Requirements 6 | 7 | 1. Design a class for matrices, and the class should contain the data of a matrix and related information such the number of rows, the number of columns, the number of channels, etc. 8 | 9 | 1. The class support different data types. It means that the matrix elements can be `unsigned char`, `short`, `int`, `float`, `double`, etc. 10 | 11 | 1. Do not use memory hard copy if a matrix object is assigned to another. Please carefully handle the memory management to avoid memory leak and to release memory multiple times. 12 | 13 | 1. Implement some frequently used operators including but not limit to `=`, `==`, `+`, `-`, `*`, etc. Surely the matrix multiplication in Project 3 should be included. 14 | 15 | 1. Implement region of interest (ROI) to avoid memory hard copy. 16 | 17 | 1. Test your program on X86 and ARM platforms, and describe the differences. 18 | 19 | 1. Class `cv::Mat` is a good example for this project. https://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html 20 | 21 | ## Rules: 22 | 23 | 1. Please submit your project report before its deadline. After the deadline, **23:59 on Nov. 28th**, (even 1 second), **0 score!**. 24 | 25 | 1. Please submit the files as: report.pdf, source1.c, source2.c, header.h. I think you do not need too many files for the project. Please do **NOT** put the files into a compressed one. 26 | 27 | 1. You score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 28 | 29 | 1. Please pay more attention to your code style. After all this is not ACM-ICPC contest. You have enough time to write code with both correct result and good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 30 | -------------------------------------------------------------------------------- /projects/2021Fall/project5-introduction.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/projects/2021Fall/project5-introduction.pptx -------------------------------------------------------------------------------- /projects/2022Fall/project1.md: -------------------------------------------------------------------------------- 1 | # A Simple Calculator 2 | 3 | Implement a calculator which can multiply two numbers. 4 | 5 | ## Requirements 6 | 7 | 1. When you run the program as follows, it will output the expression and the result. **The two numbers should be input through the command line arguments**. If the two numbers are integers, the program will multiply them in integer format. 8 | 9 | ```bash 10 | $./mul 2 3 11 | 2 * 3 = 6 12 | ``` 13 | 14 | 2. If the input contains some non-integer numbers, the program will try to interpret the input as floating-point numbers. 15 | 16 | ```bash 17 | ./mul 3.1416 2 18 | 3.1416 * 2 = 6.2832 19 | ./mul 3.1415 2.0e-2 20 | 3.1415 * 0.02 = 0.062832 21 | ``` 22 | 23 | 3. It can tell that the input is not a number. 24 | ```bash 25 | ./mul a 2 26 | The input cannot be interpret as numbers! 27 | ``` 28 | 29 | 4. If you input some big integers, what will happen? Please describe some possible solutions, and try to implement them. 30 | 31 | ```bash 32 | ./mul 1234567890 1234567890 33 | ``` 34 | 35 | 5. If you input some big floating-point numbers, what will happen? Please describe some possible solutions, and try to implement them. 36 | 37 | ```bash 38 | ./mul 1.0e200 1.0e200 39 | ``` 40 | 41 | 6. Some others which can improve the program. 42 | 43 | ## Rules: 44 | 45 | 1. Please submit your project report before its deadline. After the deadline (even 1 second), **0 score!**. The deadline is 23:59 on Sep. 25. 46 | 1. Please submit two separate files: report.pdf and source.cpp. Please do **NOT** put the two files into a compressed one. 47 | 1. Your score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 48 | 1. Please pay more attention to your code style. This is not ACM-ICPC contest. You have enough time to write code with both correct results and a good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 49 | -------------------------------------------------------------------------------- /projects/2022Fall/project2.md: -------------------------------------------------------------------------------- 1 | # Project 2: A Better Calculator 2 | 3 | Please implement a much better calculator than that in Project 1. The programming language can be C or C++. 4 | 5 | ## Requirements 6 | 7 | 1. When you run your program and input an express in a line as follows, it can output the correct results. The operator precedence (order of operations) should be correct. 8 | ``` 9 | 2+3 10 | 5 11 | 5+2*3 12 | 11 13 | ``` 14 | 1. Use parentheses to enforce the priorities. 15 | ``` 16 | (5+2)*3 17 | 21 18 | ``` 19 | 1. Variables can be defined as follows. 20 | ``` 21 | x=3 22 | y=6 23 | x+2*y 24 | 15 25 | ``` 26 | 1. Some math functions can be supported. 27 | ``` 28 | sqrt(3.0) 29 | 1.7 30 | ``` 31 | 1. It can support arbitrary precision. 32 | ``` 33 | 999999999999999999999999999.222222222 + 1.0 34 | 1000000000000000000000000000.222222222 35 | ``` 36 | 1. More features can be found in the calculator BC in Unix-like systems. You can visit this page for more information. https://www.gnu.org/software/bc/manual/html_mono/bc.html 37 | 38 | 1. Please use CMake to manage the source files if there are several. 39 | 40 | 1. Hosting your source code at GitHub.com is an option. You are strongly recommended to create a repository at GitHub.com to hold your source code for this project. Git is a good tool for version control. If so, you can just put a link in the report of the project, and do not need to upload the source code to Blackboard. If you do not host your source code at GitHub.com, please upload your source with your report to Blackboard. 41 | 42 | 43 | ## Rules: 44 | 45 | 1. Please submit your project report before its deadline. After the deadline (even 1 second), 0 score! 46 | 1. If you only implement requirements 1 and 2, the upper boundary of your score is 80. For a better score, you should implement the rest requirements. 47 | 1. Your score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 48 | 1. Please pay more attention to your code style. This is not ACM-ICPC contest. You have enough time to write code with both correct results and a good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 49 | -------------------------------------------------------------------------------- /projects/2022Fall/project3.md: -------------------------------------------------------------------------------- 1 | # Project 3: A Libray for Matrix Operations in C 2 | 3 | ## Requirements 4 | 5 | 1. The programming language can only be C, not C++. Please save your source code into `*.c` files, and compile them using a C compiler such as gcc (not g++). Try to use Makefile or CMake to manage your source code. 6 | 7 | 1. Design a `struct` for matrices, and the `struct` should contain the data of a matrix, the number of columns, the number of rows, etc. 8 | 9 | 1. Only `float` elements in a matrix are supported. You do not need to implement some other types. 10 | 11 | 1. Implement some functions to 12 | * create a matrix, `createMatrix()`. 13 | * delete a matrix, `deleteMatrix()`. 14 | * copy a matrix (copy the data from a matrix to another), `copyMatrix()`. 15 | * add two matrices, `addMatrix()`. 16 | * subtraction of two matrices, `subtractMatrix()` 17 | * add a scalar to a matrix. 18 | * subtract a scalar from a matrix. 19 | * multiply a matrix with a scalar. 20 | * multiply two matrices. 21 | * find the minimal and maximal values of a matrix. 22 | * some other functions needed 23 | 24 | 1. The designed functions should be safe and easy to use. Suppose you are designing a library for others to use. You do not need to focus on the optimization in this project, ease of use is more important. 25 | 26 | ## Rules: 27 | 28 | 1. Please submit your project report before its deadline. After the deadline, **23:59 on Oct. 30**, (even 1 second), **0 score!**. 29 | 1. Please submit the files as: report.pdf, source1.c, source2.c, header.h. I think you do not need more than 5 files for the project. Please do **NOT** put the files into a compressed one. 30 | 1. Your score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 31 | 1. Please pay more attention to your code style. This is not ACM-ICPC contest. You have enough time to write code with both correct results and a good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 32 | 33 | -------------------------------------------------------------------------------- /projects/2022Fall/project4.md: -------------------------------------------------------------------------------- 1 | # Project 4: Matrix Multiplication in C 2 | 3 | Please implement matrix multiplication in C and try your best to improve its speed. The project is an improvement of Project 3. You can reuse the source code in Project 3, but should present your improvements and different parts in the report. 4 | 5 | ## Requirements 6 | 7 | 1. Implement a function `matmul_plain()` in a straightforward way using several loops as the benchmark. 8 | 9 | 1. Implement a function `matmul_improved()` using SIMD, OpenMP and other technologies to improve the speed. You can compare it with `matmul_plain(`)`. 10 | 11 | 1. Test the performance using 16x16, 128x128, 1Kx1K, 8Kx8K and 64Kx64K matrices. You can generate some matrics with random values to test your function. 12 | 13 | 1. Compare your implementation with the matrix multiplication in OpenBLAS (https://www.openblas.net/). The results by your implementation should be the same or very similar with those by OpenBLAS. Can your implementation be as fast as OpenBLAS? 14 | 15 | 1. [Optional] Test your program on X86 and ARM platforms, and describe the differences. 16 | 17 | ## Rules: 18 | 19 | 1. Please submit your project report before its deadline. After the deadline, **23:59 on Nov. 27**, (even 1 second), **0 score!**. 20 | 21 | 1. Please submit the files as: report.pdf, source1.c, source2.c, header.h. You can also just put the link of your GitHub repository in your report, and do not need to submit source files. Please do **NOT** put the files into a compressed one. 22 | 23 | 1. Your score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 24 | 25 | 1. Please pay more attention to your code style. This is not ACM-ICPC contest. You have enough time to write code with both correct results and a good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 26 | 27 | -------------------------------------------------------------------------------- /projects/2022Fall/project5.md: -------------------------------------------------------------------------------- 1 | # Project 5: A Class for Matrices 2 | 3 | Please use C++ to implement a class. 4 | 5 | ## Requirements 6 | 7 | 1. Design a class for matrices, and the class should contain the data of a matrix and related information such the number of rows, the number of columns, the number of channels, etc. 8 | 9 | 1. The class should support different data types. It means that the matrix elements can be `unsigned char`, `short`, `int`, `float`, `double`, etc. 10 | 11 | 1. Do not use memory hard copy if a matrix object is assigned to another. Please carefully handle the memory management to avoid memory leaks and to release memory multiple times. 12 | 13 | 1. Implement some frequently used operators including but not limited to `=`, `==`, `+`, `-`, `*`, etc. Surely the matrix multiplication in Project 4 can be included. 14 | 15 | 1. Implement region of interest (ROI) to avoid memory hard copy. 16 | 17 | 1. [Optional] Test your program on X86 and ARM platforms, and describe the differences. 18 | 19 | 1. [Tip] Class `cv::Mat` is a good example for this project. https://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html 20 | 21 | ## Rules: 22 | 1. Please submit your project report before its deadline. After the deadline, **23:59 on Dec. 18**, (even 1 second), **0 score!**. 23 | 24 | 1. Please submit the files as: report.pdf, source1.c, source2.c, header.h. You can also just put the link of your GitHub repository in your report, and do not need to submit source files. Please do **NOT** put the files into a compressed one. 25 | 26 | 1. Your score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 27 | 28 | 1. Please pay more attention to your code style. This is not ACM-ICPC contest. You have enough time to write code with both correct results and a good code style. You will get deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 29 | 30 | -------------------------------------------------------------------------------- /projects/2023Spring/Project5.md: -------------------------------------------------------------------------------- 1 | # Project 5: General Matrix Multiplication 2 | 3 | The BLAS (Basic Linear Algebra Subprograms) are routines/functions that provide standard building blocks for performing basic vector and matrix operations. There are 3 levels of routines. General matrix multiplication (GEMM) is one of the most frequently used functions in BLAS libraries. The definition of GEMM in a BLAS library is $\boldsymbol{C} \leftarrow \alpha \boldsymbol{A} \boldsymbol{B} + \beta \boldsymbol{C}$, where $\boldsymbol{A}$ and $\boldsymbol{B}$ are two matrices of the same type and the same size, $\alpha$ and $\beta$ are two scalars. 4 | 5 | Please implement GEMM for `double` matrices in C or C++. Please put all your efforts into efficiency. 6 | 7 | ## Requirements 8 | 9 | 1. The interface of the function should be consistent with the OpenBLAS libray, and it is `cblas_dgemm()` in the file https://github.com/xianyi/OpenBLAS/blob/develop/cblas.h. The example to call `cblas_dgemm()` is at https://gist.github.com/xianyi/6930656. 10 | 11 | 1. Test the performance using some matrices of different sizes. You can generate some matrics with random values to test your function. 12 | 13 | 1. Compare your implementation with the `cblas_dgemm()` in OpenBLAS. The results of your implementation should be the same or very similar to those of OpenBLAS. 14 | 15 | 1. Try to improve the speed of your implementation, and make it close to the speed of OpenBLAS. 16 | 17 | 1. [Optional] Test your program on X86 and ARM platforms, and describe the differences. 18 | 19 | ## The Report 20 | 21 | 1. The submitted report should contain the design, implementation, and evaluation of the function. 22 | 23 | 2. Presentation of the project highlighting the key features and results. 24 | 25 | ## Rules: 26 | 27 | 1. The project report and the source code must be submitted before the deadline. Any submission after the deadline (even by 1 second) will result in **a score of 0**. The deadline is 23:59 on May 28. 28 | 29 | 1. The files should be submitted as report.pdf, xxx.cpp, yyy.cpp zzz.h. The files should **NOT** be compressed into one. 30 | 31 | 1. The score will depend on the quality of both the source code and the report. The report should be easy to understand and provide a clear description of the project, especially the highlights. 32 | 33 | 1. Attention should be paid to code style. Adequate time is given for code to be written correctly and with good style. Deductions will be made for poor code style. Code style guides, such as the Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html), can be used as a reference. 34 | 35 | -------------------------------------------------------------------------------- /projects/2023Spring/project1.md: -------------------------------------------------------------------------------- 1 | # A simple calculator 2 | 3 | Implement a calculator which can add, subtract, multiply and divide two numbers. 4 | 5 | ## Requirements 6 | 7 | 1. The programming language should only be C, **NOT** C++. Please save your source code into a `*.c` file, and compile it using a C compiler such as gcc (not g++). 8 | 9 | 1. When you run the program as follows, it will print the expression and the result. **The two numbers should be input through the command line arguments**. 10 | 11 | ```bash 12 | $./calculator 2 + 3 13 | 2 + 3 = 5 14 | $./calculator 2 - 3 15 | 2 - 3 = -1 16 | $./calculator 2 * 3 17 | 2 * 3 = 6 18 | $./calculator 2 / 3 19 | 2 / 3 = 0.66666667 20 | ``` 21 | 22 | 1. It can tell the reason why the operation cannot be carried out. 23 | ```bash 24 | ./calculator 3.14 / 0 25 | A number cannot be divied by zero. 26 | ``` 27 | 28 | 1. It can tell the reason when the input is not a number. 29 | ```bash 30 | ./calculator a * 2 31 | The input cannot be interpret as numbers! 32 | ``` 33 | 34 | 1. If you input some big numbers, what will happen? Please provide some possible solutions, and try to implement them. 35 | 36 | ```bash 37 | ./calculator 987654321 * 987654321 # The result should be 975461057789971041 38 | ``` 39 | ```bash 40 | ./calculator 1.0e200 1.0e200 # The result should be 1.0e400 41 | ``` 42 | 43 | 6. Some others which can improve the program. 44 | 45 | ## Rules: 46 | 47 | 1. Please submit your project report before its deadline. After the deadline (even 1 second), **0 score!** The deadline is 23:59 on March 5. 48 | 49 | 1. Please submit the files as: report.pdf, xxx.c, Please do **NOT** put the files into a compressed one. 50 | 51 | 1. Your score will also depend on the quality of your source code and your report. Your report should be easy to understand and describe your work well, especially the highlights of your work. 52 | 53 | 1. Please pay more attention to your code style. This is not ACM-ICPC contest. You have enough time to write code with both correct results and a good code style. You will get a deduction if your code style is terrible. You can read Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html ) or some other guide for code style. 54 | 55 | -------------------------------------------------------------------------------- /projects/2023Spring/project2.md: -------------------------------------------------------------------------------- 1 | # Computing the dot product of two vectors 2 | 3 | In this project, we aim to implement and compare two programs that compute the dot product of two vectors. One program will be implemented in C or C++, and the other in Java. The data type of the vectors can be int, float, double, or others. 4 | 5 | ## Requirements 6 | 7 | 1. Implement a program in C or C++ and another in Java to compute the dot product of two vectors. 8 | 9 | 1. Measure the time of the computation. As the length of the vectors increases, the time should increase too. 10 | 11 | 1. Compare the performance of the two programs and explain the reason for any observed differences. 12 | 13 | 1. Perform additional comparisons and analysis to identify any interesting insights. 14 | 15 | 16 | ## Tips: 17 | 18 | 1. As efficiency is the primary focus, random values can be used to generate vectors. 19 | 20 | 2. There is no need to customize a data type of arbitrary precision. 21 | 22 | 3. A long vector/array can be generated using `float * vec1 = (float*)malloc(n * sizeof(float));`. 23 | 24 | ## Rules: 25 | 26 | 1. The project report and the source code must be submitted before the deadline. Any submission after the deadline (even by 1 second) will result in **a score of 0**. The deadline is 23:59 on March 26. 27 | 28 | 1. The files should be submitted as report.pdf, xxx.c, and Xxx.Java. The files should **NOT** be compressed into one. 29 | 30 | 1. The score will depend on the quality of both the source code and the report. The report should be easy to understand and provide a clear description of the project, especially the highlights. 31 | 32 | 1. Attention should be paid to code style. Adequate time is given for code to be written correctly and with good style. Deductions will be made for poor code style. Code style guides, such as the Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html), can be used as a reference. 33 | 34 | -------------------------------------------------------------------------------- /projects/2023Spring/project3.md: -------------------------------------------------------------------------------- 1 | # Implementation of Convolutional Layer in Deep Learning using C 2 | 3 | Please design a function to implement the convolutional layer in deep learning using C (not C++) programming language. Convolutional Neural Networks (CNNs) are a popular deep learning technique for image and video processing. The goal of this project is to enable students to improve the efficiency of a program. 4 | 5 | ## Suggested steps 6 | 7 | 1. Understanding Convolutional Layers: Please learn about convolution operation, kernel size, padding, and strides. 8 | 9 | 2. Defining Data Structures: You should define a data structure for the input image, kernels, and output feature map. The data is in 3D (width, height, and the number of channels). Even `float16` and `int8` are also popular in deep learning, only `float32` is needed for this project. 10 | 11 | 3. Implementing Convolution Operation: You can just design a function (surely some other functions can be called by it) that takes an input image, some kernels and other parameters needed. 12 | 13 | 4. Testing: Test the function, and check if the result is correct. 14 | 15 | 5. Improve the Efficiency: If you have time, please improve the efficiency of the function. You should provide some statistical data to show its efficiency on 1x1, 3x3 and 5x5 kernels. 16 | 17 | ## The Report 18 | 19 | 1. The submitted report should contain the design, implementation, and evaluation of the function. 20 | 21 | 2. Presentation of the project highlighting the key features and results. 22 | 23 | ## Rules: 24 | 25 | 1. The project report and the source code must be submitted before the deadline. Any submission after the deadline (even by 1 second) will result in **a score of 0**. The deadline is 23:59 on April 22 (**Saturday**). 26 | 27 | 1. The files should be submitted as report.pdf, xxx.c, yyy.c zzz.h. The files should **NOT** be compressed into one. 28 | 29 | 1. The score will depend on the quality of both the source code and the report. The report should be easy to understand and provide a clear description of the project, especially the highlights. 30 | 31 | 1. Attention should be paid to code style. Adequate time is given for code to be written correctly and with good style. Deductions will be made for poor code style. Code style guides, such as the Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html), can be used as a reference. 32 | 33 | -------------------------------------------------------------------------------- /projects/2023Spring/project4.md: -------------------------------------------------------------------------------- 1 | # Project 4: A Class for the Data Blobs in Convolutional Neural Networks 2 | 3 | Please use C++ to design a class, and test it in a `main()` function to make sure it can work properly. 4 | 5 | ## Requirements 6 | 7 | 1. Design a class for the data blobs in Convolutional Neural Networks. It can be used for the input, output and kernels of a convolutional layer. The class should contain the data of a data blob and related information such the number of rows, the number of columns, the number of channels, etc. 8 | 9 | 1. The class should support different data types. It means that the elements can be `unsigned char`, `short`, `int`, `float`, `double`, etc. 10 | 11 | 1. Do not use memory hard copy if a data blob is assigned to another. Please carefully handle the memory management to avoid memory leaks and to release memory multiple times. 12 | 13 | 1. Implement some frequently used operators including but not limited to `=`, `==`, `+`, `-`, `*`, etc. 14 | 15 | 1. [Optional] Test your program on X86 and ARM platforms, and describe the differences. 16 | 17 | 1. [Tip] Class `cv::Mat` is a good example for this project. https://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html 18 | 19 | 1. [Key point] The most important part of this project is memory management. The class should be robust and easy to use. 20 | 21 | ## The Report 22 | 23 | 1. The submitted report should contain the design, implementation, and evaluation of the function. 24 | 25 | 2. Presentation of the project highlighting the key features and results. 26 | 27 | ## Rules: 28 | 29 | 1. The project report and the source code must be submitted before the deadline. Any submission after the deadline (even by 1 second) will result in **a score of 0**. The deadline is 23:59 on May 14. 30 | 31 | 1. The files should be submitted as report.pdf, xxx.cpp, yyy.cpp zzz.h. The files should **NOT** be compressed into one. 32 | 33 | 1. The score will depend on the quality of both the source code and the report. The report should be easy to understand and provide a clear description of the project, especially the highlights. 34 | 35 | 1. Attention should be paid to code style. Adequate time is given for code to be written correctly and with good style. Deductions will be made for poor code style. Code style guides, such as the Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html), can be used as a reference. 36 | 37 | -------------------------------------------------------------------------------- /projects/2024Spring/project5.md: -------------------------------------------------------------------------------- 1 | # Project 5: GPU Acceleration with CUDA 2 | 3 | ## Requirements 4 | 5 | 1. Implement the expression **B** = *a* **A** + *b*, where *a* and *b* are scalars, **A** and **B** are matrices of the same size. You can implement it by modifying the example `matadd.cu`. 6 | 7 | 2. Compare the matrix multiplication by OpenBLAS on CPU with that by cuBLAS on GPU. cuBLAS is a GPU-accelerated library provided by NVIDIA. Do not use some huge matrics, and 4096x4096 should be large enough. We have a lot of students to share the server. Surely you can use your computer if you have an NVIDIA GPU. 8 | 9 | 3. (Optional) Something interesting on GPU. 10 | 11 | ## Tips 12 | 13 | 1. The function in cuBLAS is `cublasSgemm()`. 14 | 15 | 2. Our course server will be very busy in the last few days to the deadline. 16 | 17 | ## Rules 18 | 19 | 1. **Deadline**: Please submit your project report before its deadline. The deadline is **23:59, June 2**. After the deadline (even 1 second), **0 score!** No deadline extension for any students. 20 | 21 | 22 | 1. **Format**: Please submit the files as: *.pdf, xxx.cu, xxx.h. Please do **NOT** put the files into a compressed one. To uncompress a lot of files will cost time for instructors. PDF format can make the layout of the report to be consistent on any computer. 23 | 24 | 25 | 1. **Report**: Your score will also depend on the quality of your source code **and your report**. Your report should be easy to understand and describe your work well, especially the highlights of your work. If you do not know how to write the report, just assume you are a developer in a company and are reporting to your manager that you have developed a good calculator. 26 | 27 | 1. **Code style**: Please pay more attention to your code style. This is not ACM-ICPC contest. You have enough time to write code with both correct results and a good code style. You will get a deduction if your code style is terrible. You can read Google C++ Style Guide () or some other guide for code style. You may lose points on your project if your code is ugly. 28 | 29 | 1. **ChatGPT**: You can use ChatGPT as your personal coach. Such as you can use ChatGPT or some other similar tools to polish the text in your report. But ChatGPT can also generate some rubbish that looks good but contains nothing. It will waste the time of the instructor to review those empty words, and also make you lose points on your project. ChatGPT can also generate a framework of the source code, and help improve the quality of your source code. If you use it for that, please mention it in the report. You are responsible for all materials you submit, not ChatGPT. -------------------------------------------------------------------------------- /projects/2025Spring/project2.md: -------------------------------------------------------------------------------- 1 | # Computing the dot product of two vectors 2 | 3 | This project involves implementing and comparing two programs that calculate the dot product of vectors - one in C and another in Java. The implementations will support various numeric data types including integers (int, short, signed char) and floating-point numbers (float, double). 4 | 5 | ## Requirements 6 | 7 | 1. Develop separate programs in C and Java that compute the dot product of two vectors. 8 | 9 | 1. Implement execution time measurement for the computation. The measured time should demonstrate a positive correlation with increasing vector lengths. 10 | 11 | 1. Conduct a performance comparison between the C and Java implementations. Analyze and explain any observed performance differences, considering various data types (`float`, `double`, `int`, `short`, `signed char`). Investigate whether the C implementation demonstrates significant speed advantages over Java. 12 | 13 | 1. Extend the analysis to identify noteworthy patterns or insights, such as performance variations across different data types, impact of language-specific optimizations, memory usage characteristics. 14 | 15 | 16 | ## Tips: 17 | 18 | 1. As efficicomputational efficiency is the primary focus, you can use randomly generated vector values. 19 | 20 | 1. Use native data types directly. No custom arbitrary-precision types are required. 21 | 22 | 1. Employ precise timing mechanisms: 23 | * In C: Use `` functions. But be careful that function `clock()` may not provide correct time. 24 | * In Java: Utilize `System.nanoTime()` 25 | 26 | ## Rules: 27 | 28 | 1. The project report and the source code must be submitted before the deadline. Any submission after the deadline (even by 1 second) will result in **a score of 0**. The deadline is 23:59 on March 30. 29 | 30 | 1. The files should be submitted as report.pdf, dotproduct.c, and Dotproduct.java. Use exact filename capitalization and extensions. The files should **NOT** be compressed into one. 31 | 32 | 1. The score will depend on the quality of both the source code and the report. The report should be easy to understand and provide a clear description of the project, especially the highlights. 33 | 34 | 1. Attention should be paid to code style. Adequate time is given for code to be written correctly and with good style. Deductions will be made for poor code style. Code style guides, such as the Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html), can be used as a reference. 35 | 36 | -------------------------------------------------------------------------------- /projects/2025Spring/project3.md: -------------------------------------------------------------------------------- 1 | # BMP Image Processing 2 | 3 | Write a program in C (not C++) that can read a BMP image file, modify the image, and save the modified version as a new BMP file. 4 | 5 | ## Requirements 6 | 7 | 1. The program must use only standard C libraries such as stdio.h, stdlib.h, and math.h. Third-party image processing libraries like OpenCV are not allowed. 8 | 9 | 1. BMP (Bitmap) files come in multiple formats, primarily differing in color depth, compression methods, and header versions. The program should focus on handling ​24-bit uncompressed BMPs, as they are the most common and easiest to work with. 10 | 11 | 1. A `struct` should be defined to store the image data in memory after loading it from the BMP file. 12 | 13 | 1. The program should support basic image processing operations, such as: 14 | 15 | * Adjusting brightness by adding a fixed value to all pixel values (e.g., `$ ./bmpedit -i input.bmp -o output.bmp -op add 50`). 16 | * Blending two images by averaging their pixel values (e.g., `$ ./bmpedit -i input1.bmp -i input2.bmp -o output.bmp -op average`). 17 | * Some other image processing functions. 18 | 19 | 1. Image processing is time consuming. Please optimize the source code to make it running fast. 20 | 21 | 1. The program should be **​robust** (with good memory management, and handling errors gracefully) and ​user-friendly (with clear command-line usage). 22 | 23 | 1. You are **encouraged** to use an AI tool, such as DeepSeek, to generate a framework of the source code, and help improve the quality of your source code. Please describe how you improve your source code and your report using the tool. But do not generate some rubbish words and source code. 24 | 25 | ## Rules: 26 | 27 | 1. The project report and the source code must be submitted before the deadline. Any submission after the deadline (even by 1 second) will result in **a score of 0**. The deadline is 23:59 on April 13. 28 | 29 | 1. The files should be submitted as report.pdf, *.c (it's better to have one *.c file). Use exact filename capitalization and extensions. The files should **NOT** be compressed into one. 30 | 31 | 1. The score will depend on the quality of both the source code and the report. The report should be easy to understand and provide a clear description of the project, especially the highlights. 32 | 33 | 1. Attention should be paid to code style. Adequate time is given for code to be written correctly and with good style. Deductions will be made for poor code style. Code style guides, such as the Google C++ Style Guide (http://google.github.io/styleguide/cppguide.html), can be used as a reference. 34 | 35 | -------------------------------------------------------------------------------- /rust/Rust-Lab1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/rust/Rust-Lab1.pdf -------------------------------------------------------------------------------- /rust/Rust-Lab1.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/rust/Rust-Lab1.pptx -------------------------------------------------------------------------------- /rust/Rust-Lab2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/rust/Rust-Lab2.pdf -------------------------------------------------------------------------------- /rust/Rust-Lab2.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/rust/Rust-Lab2.pptx -------------------------------------------------------------------------------- /rust/Rust-Lecture1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/rust/Rust-Lecture1.pdf -------------------------------------------------------------------------------- /rust/Rust-Lecture1.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/rust/Rust-Lecture1.pptx -------------------------------------------------------------------------------- /rust/Rust-Lecture2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/rust/Rust-Lecture2.pdf -------------------------------------------------------------------------------- /rust/Rust-Lecture2.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/rust/Rust-Lecture2.pptx -------------------------------------------------------------------------------- /rust/hello/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /rust/hello/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /week01/Lab01.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week01/Lab01.pdf -------------------------------------------------------------------------------- /week01/Lab01.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week01/Lab01.pptx -------------------------------------------------------------------------------- /week01/Lecture01.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week01/Lecture01.pdf -------------------------------------------------------------------------------- /week01/Lecture01.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week01/Lecture01.pptx -------------------------------------------------------------------------------- /week01/examples/argument.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | int main(int argc, char * argv[]) 5 | { 6 | for (int i = 0; i < argc; i++) 7 | cout << i << ": " << argv[i] << endl; 8 | } 9 | -------------------------------------------------------------------------------- /week01/examples/hello.cpp: -------------------------------------------------------------------------------- 1 | //C++ example in C++11 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | vector msg {"Hello", "C++", "World", "!"}; 11 | 12 | for (const string& word : msg) 13 | { 14 | cout << word << " "; 15 | } 16 | cout << endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /week01/examples/lab/add.cpp: -------------------------------------------------------------------------------- 1 | #include "add.h" 2 | 3 | int Add(int number1, int number2); 4 | { 5 | return n1 + n2; 6 | } -------------------------------------------------------------------------------- /week01/examples/lab/add.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | int add(int n1, int n2); 4 | -------------------------------------------------------------------------------- /week01/examples/lab/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Add.h" 3 | 4 | using namespace std; 5 | int main() 6 | { 7 | int num1 = 2147483647; 8 | int num2 = 1; 9 | int result = 0; 10 | 11 | result = add(num1, num2); 12 | 13 | cout << “The result is ” << result << endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /week01/examples/macro.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define PI 2.14+1.0 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | double len = 2 * PI * 3; 9 | cout << "len = " << len << endl; //it will output 7.28, nor 18.84 10 | } 11 | -------------------------------------------------------------------------------- /week01/examples/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mul.hpp" 3 | 4 | using namespace std; 5 | int main() 6 | { 7 | int a = 0, b = 0; 8 | int result = 0; 9 | 10 | cout << "Pick two integers:"; 11 | cin >> a; 12 | cin >> b; 13 | 14 | result = mul(a, b); 15 | 16 | cout << "The result is " << result << endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /week01/examples/mainmul.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int mul(int a, int b) 6 | { 7 | return a * b; 8 | } 9 | int main() 10 | { 11 | int a = 0, b = 0; 12 | int result = 0; 13 | 14 | cout << "Pick two integers:"; 15 | cin >> a; 16 | cin >> b; 17 | 18 | result = mul(a, b); 19 | 20 | cout << "The result is " << result << endl; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /week01/examples/mul.cpp: -------------------------------------------------------------------------------- 1 | #include "mul.hpp" 2 | 3 | int mul(int a, int b) 4 | { 5 | int c = a / b; 6 | return c; 7 | } 8 | -------------------------------------------------------------------------------- /week01/examples/mul.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | int mul(int a, int b); 4 | -------------------------------------------------------------------------------- /week02/Lab02.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week02/Lab02.pdf -------------------------------------------------------------------------------- /week02/Lab02.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week02/Lab02.pptx -------------------------------------------------------------------------------- /week02/Lecture02.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week02/Lecture02.pdf -------------------------------------------------------------------------------- /week02/Lecture02.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week02/Lecture02.pptx -------------------------------------------------------------------------------- /week02/examples/bool.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | bool b1 = true; 7 | int i = b1; 8 | bool b2 = -256; 9 | cout << "i=" << i << endl; 10 | cout << "b1=" << b1 << endl; 11 | cout << "b2=" << b2 << endl; 12 | cout << true << endl; 13 | return 0; 14 | } -------------------------------------------------------------------------------- /week02/examples/char.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | char c1 = 'C'; 7 | char c2 = 80; 8 | char c3 = 0x50; 9 | char16_t c4 = u'于'; 10 | char32_t c5 = U'于'; 11 | cout << c1 << ":" << c2 << ":"<< c3 << endl; 12 | cout << +c1 << ":" << +c2 << ":" << +c3 << endl; 13 | cout << c4 << endl; 14 | cout << c5 << endl; 15 | 16 | return 0; 17 | } 18 | 19 | -------------------------------------------------------------------------------- /week02/examples/conversion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int num_int1 = 9; // assigning an int value to num_int1 7 | int num_int2 = 'C'; // implicit conversion 8 | int num_int3 = (int)'C'; // explicit conversion, C-style 9 | int num_int4 = int('C'); // explicit conversion, function style 10 | int num_int5 = 2.8; //implicit conversion 11 | float num_float = 2.3; // implicit conversion from double to float, may loss precision 12 | short num_short = 650000; 13 | 14 | cout << "num_short = " << num_short << endl; 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /week02/examples/float.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | float f1 = 1.2f; 7 | float f2 = f1 * 1000000000000000; 8 | cout << std::fixed << std::setprecision(15) << f1 << endl; 9 | cout << std::fixed << std::setprecision(1) << f2 << endl; 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /week02/examples/init.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int num1; //bad: uninitialized variable 6 | int num2; //bad: uninitialized variable 7 | cout << "num1 = " << num1 << endl; 8 | cout << "num2 = " << num2 << endl; 9 | } 10 | -------------------------------------------------------------------------------- /week02/examples/intmax.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | cout << "INT8_MAX=" << INT8_MAX << endl; 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /week02/examples/nan.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | float f1 = 2.0f / 0.0f; 7 | float f2 = 0.0f / 0.0f; 8 | cout << f1 << endl; 9 | cout << f2 << endl; 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /week02/examples/overflow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int a = 56789; 7 | int b = 56789; 8 | int c = a * b; 9 | cout << "c = " << c << endl; 10 | 11 | // unsigned int c1 = a * b; //danger operation 12 | // cout << "c1 = " << c1 << endl; 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /week02/examples/precision.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | float f1 = 23400000000; 7 | float f2 = f1 + 10; 8 | 9 | cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point 10 | cout << "f1 = " << f1 << endl; 11 | cout << "f2 = " << f2 << endl; 12 | cout << "f1 - f2 = " << f1 - f2 << endl; 13 | cout << "(f1 - f2 == 0) = " << (f1 - f2 == 0) << endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /week02/examples/size.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int i = 0; 7 | short s = 0; 8 | cout << "sizeof(int)=" << sizeof(int) << endl; 9 | cout << "sizeof(i)=" << sizeof(i) << endl; 10 | cout << "sizeof(s)=" << sizeof(s) << endl; 11 | cout << "sizeof(long)=" << sizeof(long) << endl; 12 | cout << "sizeof(size_t)=" << sizeof(size_t) << endl; 13 | return 0; 14 | } -------------------------------------------------------------------------------- /week02/images/integer-sign-bit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week02/images/integer-sign-bit.png -------------------------------------------------------------------------------- /week03/Lab03.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week03/Lab03.pdf -------------------------------------------------------------------------------- /week03/Lab03.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week03/Lab03.pptx -------------------------------------------------------------------------------- /week03/Lecture03.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week03/Lecture03.pdf -------------------------------------------------------------------------------- /week03/Lecture03.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week03/Lecture03.pptx -------------------------------------------------------------------------------- /week03/examples/for.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int sum = 0; 6 | for(int i = 0; i < 10; i++) 7 | { 8 | sum += i; 9 | cout << "Line " << i << endl; 10 | } 11 | cout << "sum = " << sum << endl; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /week03/examples/goto.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | float mysquare(float value) 6 | { 7 | float result = 0.0f; 8 | 9 | if(value >= 1.0f || value <= 0) 10 | { 11 | cerr << "The input is out of range." << endl; 12 | goto EXIT_ERROR; 13 | } 14 | result = value * value; 15 | return result; 16 | 17 | EXIT_ERROR: 18 | //do sth such as closing files here 19 | return 0.0f; 20 | } 21 | 22 | int main() 23 | { 24 | float value; 25 | cout << "Input a floating-point number." << endl; 26 | cin >> value; 27 | 28 | float result = mysquare(value); 29 | 30 | if (result > 0) 31 | cout << "The square is " << result << "." << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /week03/examples/if.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int num = 10; 7 | if (num < 5) 8 | cout << "The number is less than 5. " << endl; 9 | 10 | if (num == 5 ) 11 | { 12 | cout << "The number is 5." << endl; 13 | } 14 | else 15 | { 16 | cout << "The number is not 5." << endl; 17 | } 18 | 19 | if (num < 5) 20 | cout << "The number is less than 5." << endl; 21 | else if (num > 10) 22 | cout << "The number is greater than 10." << endl; 23 | else 24 | cout << "The number is in range [5, 10]." << endl; 25 | 26 | if(num < 20) 27 | if(num < 5) 28 | cout << "The number is less than 5" << endl; 29 | else 30 | cout << "Where I'm?" << endl; 31 | 32 | int * p = new int[1024]; 33 | if (p) 34 | cout << "Memory has been allocated." << endl; 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /week03/examples/lab/Makefile: -------------------------------------------------------------------------------- 1 | # ## VERSION 1 2 | # hello: main.cpp printhello.cpp factorial.cpp 3 | # g++ -o hello main.cpp printhello.cpp factorial.cpp 4 | 5 | # ## VERSION 2 6 | # CXX = g++ 7 | # TARGET = hello 8 | # OBJ = main.o printhello.o factorial.o 9 | 10 | # $(TARGET): $(OBJ) 11 | # $(CXX) -o $(TARGET) $(OBJ) 12 | 13 | # main.o: main.cpp 14 | # $(CXX) -c main.cpp 15 | 16 | # printhello.o: printhello.cpp 17 | # $(CXX) -c printhello.cpp 18 | 19 | # factorial.o: factorial.cpp 20 | # $(CXX) -c factorial.cpp 21 | 22 | 23 | # ## VERSION 3 24 | # CXX = g++ 25 | # TARGET = hello 26 | # OBJ = main.o printhello.o factorial.o 27 | 28 | # CXXFLAGS = -c -Wall 29 | 30 | # $(TARGET): $(OBJ) 31 | # $(CXX) -o $@ $^ 32 | 33 | # %.o: %.cpp 34 | # $(CXX) $(CXXFLAGS) $< -o $@ 35 | 36 | # .PHONY: clean 37 | # clean: 38 | # rm -f *.o $(TARGET) 39 | 40 | 41 | ## VERSION 4 42 | CXX = g++ 43 | TARGET = hello 44 | SRC = $(wildcard *.cpp) 45 | OBJ = $(patsubst %.cpp, %.o, $(SRC)) 46 | 47 | CXXFLAGS = -c -Wall 48 | 49 | $(TARGET): $(OBJ) 50 | $(CXX) -o $@ $^ 51 | 52 | %.o: %.cpp 53 | $(CXX) $(CXXFLAGS) $< -o $@ 54 | 55 | .PHONY: clean 56 | clean: 57 | rm -f *.o $(TARGET) -------------------------------------------------------------------------------- /week03/examples/lab/factorial.cpp: -------------------------------------------------------------------------------- 1 | #include "functions.h" 2 | 3 | int factorial(int n) 4 | { 5 | if (n == 1) 6 | return 1; 7 | else 8 | return n * factorial(n - 1); 9 | } -------------------------------------------------------------------------------- /week03/examples/lab/functions.h: -------------------------------------------------------------------------------- 1 | #ifndef _FUNCTIONS_H_ 2 | #define _FUNCTIONS_H_ 3 | void printhello(); 4 | int factorial(int n); 5 | #endif -------------------------------------------------------------------------------- /week03/examples/lab/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "functions.h" 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | printhello(); 8 | 9 | cout << "This is main:" << endl; 10 | cout << "The factorial of 5 is: " << factorial(5) << endl; 11 | return 0; 12 | } -------------------------------------------------------------------------------- /week03/examples/lab/printhello.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "functions.h" 3 | 4 | using namespace std; 5 | 6 | void printhello() 7 | { 8 | int i = 0; 9 | cout << "Hello World!" << endl; 10 | } -------------------------------------------------------------------------------- /week03/examples/switch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | unsigned char input_char = 0; 7 | 8 | cout << "Please input a character to start." << endl; 9 | cin >> input_char; 10 | while (input_char != 'q') 11 | { 12 | switch (input_char) 13 | { 14 | case 'a': 15 | case 'A': 16 | cout << "Move left. Input 'q' to quit." << endl; 17 | break; 18 | case 'd': 19 | case 'D': 20 | cout << "Move right. Input 'q' to quit." << endl; 21 | break; 22 | default: 23 | cout << "Undefined key. Input 'q' to quit." << endl; 24 | break; 25 | } 26 | cin >> input_char; 27 | } 28 | } -------------------------------------------------------------------------------- /week03/examples/ternary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | bool isPositive = true; 7 | int factor = 0; 8 | //some operations may change isPositive's value 9 | if(isPositive) 10 | factor = 1; 11 | else 12 | factor = -1; 13 | //the if-else statement can be replaced by a ternary conditional operation 14 | factor = isPositive ? 1 : -1; 15 | 16 | //sometimes the following code can be more efficient. 17 | factor = isPositive * 2 - 1; 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /week03/examples/while.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int num = 10; 6 | while(num > 0) 7 | { 8 | cout << "num = " << num << endl; 9 | num--; 10 | } 11 | 12 | // num = 10; 13 | // do 14 | // { 15 | // cout << "num = " << num << endl; 16 | // num--; 17 | // }while (num > 0); 18 | 19 | // num = 10; 20 | // while (num > 0) 21 | // { 22 | // if (num == 5) 23 | // break; 24 | // cout << "num = " << num << endl; 25 | // num--; 26 | // } 27 | return 0; 28 | } -------------------------------------------------------------------------------- /week04/Lab04.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week04/Lab04.pdf -------------------------------------------------------------------------------- /week04/Lab04.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week04/Lab04.pptx -------------------------------------------------------------------------------- /week04/Lecture04.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week04/Lecture04.pdf -------------------------------------------------------------------------------- /week04/Lecture04.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week04/Lecture04.pptx -------------------------------------------------------------------------------- /week04/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 4: Data Structures 2 | 3 | ## Arrays (be careful of out of range) 4 | 5 | ## Array-style strings 6 | 7 | ## Structures 8 | 9 | ## Unions 10 | 11 | ## Enumerations 12 | 13 | ## Lab: 14 | 15 | * create an array and the element is of a structure 16 | * cmake (automatically generate a Makefile according to the environment). -------------------------------------------------------------------------------- /week04/array-illustration.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week04/array-illustration.xlsx -------------------------------------------------------------------------------- /week04/examples/array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int num_array1[5]; //uninitialized array, random values 6 | int num_array2[5] = {0, 1, 2, 3, 4}; //initialization 7 | 8 | for(int idx = 0; idx < 5; idx++) 9 | cout << num_array1[idx] << " "; 10 | cout << endl; 11 | 12 | for(int idx = 0; idx < 5; idx++) 13 | cout << num_array2[idx] << " "; 14 | cout << endl; 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /week04/examples/cmakedemo/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | 3 | project(hello) 4 | 5 | add_executable(hello main.cpp) 6 | -------------------------------------------------------------------------------- /week04/examples/cmakedemo/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | cout << "Hello, SUSTech." << endl; 7 | return 0; 8 | } -------------------------------------------------------------------------------- /week04/examples/const-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //float array_sum(const float *values, size_t length) 5 | //float array_sum(const float values[4], size_t length) 6 | float array_sum(const float values[], size_t length) 7 | { 8 | float sum = 0.0f; 9 | for (int i = 0; i < length; i++) 10 | { 11 | sum += values[i]; 12 | //values[i] = 0; //error 13 | } 14 | return sum; 15 | } 16 | 17 | int main() 18 | { 19 | // const float PI = 3.1415926f; 20 | // PI += 1.f; // error 21 | // const float values[4] = {1.1f, 2.2f, 3.3f, 4.4f}; 22 | // values[0] = 1.0f; // error 23 | 24 | float values[4] = {1.1f, 2.2f, 3.3f, 4.4f}; 25 | float sum = array_sum(values, 4); 26 | 27 | cout << "sum = " << sum << endl; 28 | return 0; 29 | } -------------------------------------------------------------------------------- /week04/examples/enum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | enum color {WHITE, BLACK, RED, GREEN, BLUE, YELLOW, NUM_COLORS}; 5 | enum datatype {TYPE_INT8=1, TYPE_INT16=2, TYPE_INT32=4, TYPE_INT64=8}; 6 | 7 | struct Point{ 8 | enum datatype type; 9 | union { 10 | std::int8_t data8[3]; 11 | std::int16_t data16[3]; 12 | std::int32_t data32[3]; 13 | std::int64_t data64[3]; 14 | }; 15 | }; 16 | 17 | size_t datawidth(struct Point pt) 18 | { 19 | return size_t(pt.type) * 3; 20 | } 21 | 22 | int64_t l1norm(struct Point pt) 23 | { 24 | int64_t result = 0; 25 | switch(pt.type) 26 | { 27 | case (TYPE_INT8): 28 | result = abs(pt.data8[0]) + abs(pt.data8[1]) + abs(pt.data8[2]); 29 | break; 30 | case (TYPE_INT16): 31 | result = abs(pt.data16[0]) + abs(pt.data16[1]) + abs(pt.data16[2]); 32 | break; 33 | case (TYPE_INT32): 34 | result = abs(pt.data32[0]) + abs(pt.data32[1]) + abs(pt.data32[2]); 35 | break; 36 | case (TYPE_INT64): 37 | result = abs(pt.data64[0]) + abs(pt.data64[1]) + abs(pt.data64[2]); 38 | break; 39 | } 40 | return result; 41 | } 42 | 43 | int main() 44 | { 45 | enum color pen_color = RED; 46 | pen_color = color(3); //convert int to enum 47 | cout << "We have " << NUM_COLORS << " pens." << endl; 48 | //pen_color += 1; //error! 49 | int color_index = pen_color; 50 | color_index += 1; 51 | cout << "color_index = " << color_index << endl; 52 | 53 | //declaration and initialization 54 | struct Point point1 = {.type=TYPE_INT8, .data8={-2,3,4}}; 55 | struct Point point2 = {.type=TYPE_INT32, .data32={1,-2,3}}; 56 | 57 | cout << "Data width = " << datawidth(point1) << endl; 58 | cout << "Data width = " << datawidth(point2) << endl; 59 | 60 | cout << "L1 norm = " << l1norm(point1) << endl; 61 | cout << "L1 norm = " << l1norm(point2) << endl; 62 | 63 | 64 | return 0; 65 | } -------------------------------------------------------------------------------- /week04/examples/index-bound.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int num_array[5]; 6 | 7 | for(int idx = -1; idx <= 5; idx++) //out of bounds 8 | num_array[idx] = idx * idx; 9 | 10 | for(int idx = -1; idx <= 5; idx++) //out of bounds 11 | cout << "num_array[" << idx << "] = " << num_array[idx] << endl; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /week04/examples/initchar.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | char rabbit[16] = {'P', 'e', 't', 'e', 'r'}; 8 | cout << "String length is " << strlen(rabbit) << endl; 9 | for(int i = 0; i < 16; i++) 10 | cout << i << ":" << +rabbit[i] << "(" << rabbit[i] << ")" << endl; 11 | 12 | char bad_pig[9] = {'P', 'e', 'p', 'p', 'a', ' ', 'P', 'i', 'g'}; 13 | char good_pig[10] = {'P', 'e', 'p', 'p', 'a', ' ', 'P', 'i', 'g', '\0'}; 14 | 15 | cout << "Rabbit is (" << rabbit << ")" << endl; 16 | cout << "Pig's bad name is (" << bad_pig << ")" << endl; 17 | cout << "Pig's good name is (" << good_pig << ")" << endl; 18 | 19 | char name[10] = {'Y', 'u', '\0', 'S', '.', '0'}; 20 | cout << "(" << name << ")" << endl; 21 | cout << strlen(name) << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /week04/examples/lab/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | 3 | project(hello) 4 | 5 | add_executable(hello main.cpp factorial.cpp printhello.cpp) 6 | -------------------------------------------------------------------------------- /week04/examples/lab/factorial.cpp: -------------------------------------------------------------------------------- 1 | #include "functions.h" 2 | 3 | int factorial(int n) 4 | { 5 | if (n == 1) 6 | return 1; 7 | else 8 | return n * factorial(n - 1); 9 | } -------------------------------------------------------------------------------- /week04/examples/lab/functions.h: -------------------------------------------------------------------------------- 1 | #ifndef _FUNCTIONS_H_ 2 | #define _FUNCTIONS_H_ 3 | void printhello(); 4 | int factorial(int n); 5 | #endif -------------------------------------------------------------------------------- /week04/examples/lab/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "functions.h" 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | printhello(); 8 | 9 | cout << "This is main:" << endl; 10 | cout << "The factorial of 5 is: " << factorial(5) << endl; 11 | return 0; 12 | } -------------------------------------------------------------------------------- /week04/examples/lab/printhello.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "functions.h" 3 | 4 | using namespace std; 5 | 6 | void printhello() 7 | { 8 | int i; 9 | cout << "Hello World!" << endl; 10 | } -------------------------------------------------------------------------------- /week04/examples/md-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // You must tell the function the bound of an array, 5 | // otherwise, elements cannot be accessed 6 | // if the array is a variable-length one, it may be difficult to know the bound 7 | void init_2d_array(float mat[][4], //error, arrays of unknown bound 8 | size_t rows, size_t cols) 9 | { 10 | for (int r = 0; r < rows; r++) 11 | for(int c = 0; c < cols; c++) 12 | mat[r][c] = r * c; 13 | } 14 | 15 | int main() 16 | { 17 | int mat1[2][3] = {{11,12,13}, {14,15,16}}; 18 | 19 | int rows = 5; 20 | int cols = 4; 21 | //float mat2[rows][cols]; //uninitialized array 22 | float mat2[rows][4]; //uninitialized array 23 | 24 | //init_2d_array(mat2, rows, cols); 25 | 26 | for (int r = 0; r < rows; r++) 27 | for(int c = 0; c < cols; c++) 28 | mat2[r][c] = r * c; 29 | 30 | 31 | for (int r = 0; r < rows; r++) 32 | { 33 | for(int c = 0; c < cols; c++) 34 | cout << mat2[r][c] << " "; 35 | cout << endl; 36 | } 37 | return 0; 38 | } -------------------------------------------------------------------------------- /week04/examples/stdstring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | int main() 6 | { 7 | std::string str1 = "Hello"; 8 | std::string str2 = "SUSTech"; 9 | std::string result = str1 + ", " + str2; 10 | 11 | cout << "result = " + result << endl; 12 | 13 | cout << "The length is " << result.length() << endl; 14 | 15 | cout << "str1 < str2 is " << (str1 < str2) << endl; 16 | 17 | cout << "str1[100] = (" << str1[100] << ")" << endl; 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /week04/examples/stringelement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | string str = "Hello, SUSTech!"; 8 | for(int i = 0; i <= str.length(); i++) //no bound check 9 | cout << i << ": " << str[i] << endl; 10 | 11 | return 0; 12 | } -------------------------------------------------------------------------------- /week04/examples/stringop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | char str1[] = "Hello, \0CPP"; 8 | char str2[] = "SUSTech"; 9 | char result[128]; 10 | 11 | for(int i = 0; i < 16; i++) 12 | cout << i << ":" << +str1[i] << "(" << str1[i] << ")" << endl; 13 | 14 | strcpy(result, str1); 15 | cout << "Result = " << result << endl; 16 | strcat(result, str2); 17 | cout << "Result = " << result << endl; 18 | 19 | cout << "strcmp() = " << strcmp(str1, str2) << endl; 20 | 21 | //strcat(str1, str2); //danger operation! 22 | //cout << "str1 = " << str1 << endl; 23 | } -------------------------------------------------------------------------------- /week04/examples/struct.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // typedef 6 | // struct _Student{ 7 | // char name[4]; 8 | // int born; 9 | // bool male; 10 | // } Student; 11 | 12 | struct Student{ 13 | char name[4]; 14 | int born; 15 | bool male; 16 | }; 17 | int main() 18 | { 19 | struct Student stu = {"Yu", 2000, true}; //initialization 20 | // strcpy(stu.name, "Yu"); 21 | // stu.born = 2000; 22 | // stu.male = true; 23 | 24 | printf("Student %s, born in %d, gender %s\n", 25 | stu.name, 26 | stu.born, 27 | stu.male ? "male" : "female"); 28 | 29 | struct Student students[100]; 30 | students[50].born = 2002; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /week04/examples/structpadding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Student1{ 5 | int id; 6 | bool male; 7 | char label; 8 | float weight; 9 | }; 10 | 11 | struct Student2{ 12 | int id; 13 | bool male; 14 | float weight; 15 | char label; 16 | }; 17 | 18 | int main() 19 | { 20 | cout << "Size of Student1: " << sizeof(Student1) << endl; 21 | cout << "Size of Student2: " << sizeof(Student2) << endl; 22 | return 0; 23 | } -------------------------------------------------------------------------------- /week04/examples/typedef.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef int myint; 5 | typedef unsigned char vec3b[3]; 6 | typedef struct _rgb_struct{ // name _rgb_struct can be omit 7 | unsigned char r; 8 | unsigned char g; 9 | unsigned char b; 10 | } rgb_struct; 11 | 12 | int main() 13 | { 14 | myint num = 32; 15 | 16 | // the following two lines are identical 17 | //unsigned char color[3] = {255, 0, 255}; 18 | vec3b color = {255, 0, 255}; 19 | cout << hex; 20 | cout << "R=" << +color[0] << ", "; 21 | cout << "G=" << +color[1] << ", "; 22 | cout << "B=" << +color[2] << endl; 23 | 24 | rgb_struct rgb = {0, 255, 128}; 25 | cout << "R=" << +rgb.r << ", "; 26 | cout << "G=" << +rgb.g << ", "; 27 | cout << "B=" << +rgb.b << endl; 28 | 29 | cout << sizeof(rgb.r) << endl; 30 | cout << sizeof(+rgb.r) << endl; //why 4? 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /week04/examples/union.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | union ipv4address{ 5 | std::uint32_t address32; 6 | std::uint8_t address8[4]; 7 | }; 8 | 9 | int main() 10 | { 11 | union ipv4address ip; 12 | 13 | cout << "sizeof(ip) = " << sizeof(ip) << endl; 14 | 15 | ip.address8[3] = 127; 16 | ip.address8[2] = 0; 17 | ip.address8[1] = 0; 18 | ip.address8[0] = 1; 19 | 20 | cout << "The address is " ; 21 | cout << +ip.address8[3] << "."; 22 | cout << +ip.address8[2] << "."; 23 | cout << +ip.address8[1] << "."; 24 | cout << +ip.address8[0] << endl; 25 | 26 | cout << std::hex; 27 | cout << "in hex " << ip.address32 << endl; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /week04/examples/unknow-size-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // float array_sum(float *values, size_t length) // equivalent to the next line 5 | float array_sum(float values[], size_t length) 6 | { 7 | cout << sizeof(values) << endl; // 4 or 8 8 | float sum = 0.0f; 9 | for (int i = 0; i < length; i++) 10 | { 11 | sum += values[i]; 12 | } 13 | return sum; 14 | } 15 | 16 | int main() 17 | { 18 | float values[4] = {1.1f, 2.2f, 3.3f, 4.4f}; 19 | float sum = array_sum(values, 4); 20 | 21 | cout << "sum = " << sum << endl; 22 | return 0; 23 | } -------------------------------------------------------------------------------- /week04/examples/variable-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int num_array1[5] = {0,1}; // fixed length array, initialized to {0,1,0,0,0} 6 | cout << "sizeof(num_array1) = " << sizeof(num_array1) << endl; 7 | 8 | int len = 0; 9 | while ( len < 10 ) 10 | { 11 | int num_array2[len]; //variable-length array 12 | cout << "len = " << len; 13 | cout << ", sizeof(num_array2)) = " << sizeof(num_array2) << endl; 14 | len ++; 15 | } 16 | } -------------------------------------------------------------------------------- /week05/Lab05.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/Lab05.pdf -------------------------------------------------------------------------------- /week05/Lab05.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/Lab05.pptx -------------------------------------------------------------------------------- /week05/Lecture05.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/Lecture05.pdf -------------------------------------------------------------------------------- /week05/Lecture05.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/Lecture05.pptx -------------------------------------------------------------------------------- /week05/examples/arithmetic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define PRINT_ARRAY(array, n) \ 5 | for (int idx = 0; idx < (n); idx++) \ 6 | cout << "array[" << idx << "] = " << (array)[idx] << endl; 7 | 8 | int main() 9 | { 10 | int numbers[4] = {0, 1, 2, 3}; 11 | PRINT_ARRAY(numbers, 4) 12 | 13 | int * p = numbers + 1; // point to the element with value 1 14 | p++; // point to the element with value 2 15 | 16 | cout << "numbers = " << numbers << endl; 17 | cout << "p = " << p << endl; 18 | 19 | *p = 20; //change number[2] from 2 to 20 20 | *(p-1) = 10; //change number[1] from 1 to 10 21 | p[1] = 30; //change number[3] from 3 to 30 22 | 23 | PRINT_ARRAY(numbers, 4) 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /week05/examples/bound.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int a; 7 | int num = 0; 8 | int * p = # 9 | 10 | p[-1] = 2; //out of bound 11 | p[0] = 3; //okay 12 | *(p+1) = 4; //out of bound 13 | 14 | cout << "num = " << num << endl; 15 | 16 | return 0; 17 | } -------------------------------------------------------------------------------- /week05/examples/const-pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int foo(const char * p) 5 | { 6 | // the value that p points to cannot be changed 7 | // play a trick? 8 | char * p2 = p; //syntax error 9 | //... 10 | return 0; 11 | } 12 | 13 | int main() 14 | { 15 | int num = 1; 16 | int another = 2; 17 | 18 | //You cannot change the value that p1 points to through p1 19 | const int * p1 = # 20 | *p1 = 3; //error 21 | num = 3; //okay 22 | 23 | //You cannot change value of p2 (address) 24 | int * const p2 = # 25 | *p2 = 3; //okay 26 | p2 = &another; //error 27 | 28 | //You can change neither 29 | const int* const p3 = # 30 | *p3 = 3; //error 31 | p3 = &another; // error 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /week05/examples/memoryleak.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void foo() 5 | { 6 | int* p = (int *) malloc( sizeof(int)); 7 | return; 8 | } //memory leak 9 | 10 | int main() 11 | { 12 | int * p = NULL; 13 | 14 | p = (int *) malloc(4 * sizeof(int)); 15 | // some statements 16 | p = (int *) malloc(8 * sizeof(int)); 17 | // some statements 18 | free (p); 19 | // the first memory will not be freed 20 | 21 | for(int i = 0; i < 1024; i++) 22 | { 23 | p = (int *) malloc(1024 * 1024 * 1024); 24 | } 25 | printf("End\n"); 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /week05/examples/newdelete.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Student 5 | { 6 | char name[4]; 7 | int born; 8 | bool male; 9 | }; 10 | 11 | int main() 12 | { 13 | //allocate an int, default initializer (do nothing) 14 | int * p1 = new int; 15 | //allocate an int, initialized to 0 16 | int * p2 = new int(); 17 | //allocate an int, initialized to 5 18 | int * p3 = new int(5); 19 | //allocate an int, initialized to 0 20 | int * p4 = new int{};//C++11 21 | //allocate an int, initialized to 5 22 | int * p5 = new int {5};//C++11 23 | 24 | //allocate a Student object, default initializer 25 | Student * ps1 = new Student; 26 | //allocate a Student object, initialize the members 27 | Student * ps2 = new Student {"Yu", 2020, 1}; //C++11 28 | 29 | //allocate 16 int, default initializer (do nothing) 30 | int * pa1 = new int[16]; 31 | //allocate 16 int, zero initialized 32 | int * pa2 = new int[16](); 33 | //allocate 16 int, zero initialized 34 | int * pa3 = new int[16]{}; //C++11 35 | //allocate 16 int, the first 3 element are initialized to 1,2,3, the rest 0 36 | int * pa4 = new int[16]{1,2,3}; //C++11 37 | 38 | //allocate memory for 16 Student objects, default initializer 39 | Student * psa1 = new Student[16]; 40 | //allocate memory for 16 Student objects, the first two are explicitly initialized 41 | Student * psa2 = new Student[16]{{"Li", 2000,1}, {"Yu", 2001,1}}; //C++11 42 | cout << psa2[1].name << endl; 43 | cout << psa2[1].born << endl; 44 | 45 | //deallocate memory 46 | delete p1; 47 | //deallocate memory 48 | delete ps1; 49 | 50 | //deallocate the memory of the array 51 | delete pa1; 52 | //deallocate the memory of the array 53 | delete []pa2; 54 | 55 | //deallocate the memory of the array, and call the destructor of the first element 56 | delete psa1; 57 | //deallocate the memory of the array, and call the destructors of all the elements 58 | delete []psa2; 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /week05/examples/pointer-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Student 5 | { 6 | char name[4]; 7 | int born; 8 | bool male; 9 | }; 10 | 11 | int main() 12 | { 13 | // Part One 14 | Student students[128]; 15 | Student * p0 = &students[0]; 16 | Student * p1 = &students[1]; 17 | Student * p2 = &students[2]; 18 | Student * p3 = &students[3]; 19 | 20 | printf("p0 = %p\n", p0); 21 | printf("p1 = %p\n", p1); 22 | printf("p2 = %p\n", p2); 23 | printf("p3 = %p\n", p3); 24 | 25 | //the same behavior 26 | students[1].born = 2000; 27 | p1->born = 2000; 28 | 29 | // Part Two 30 | printf("&students = %p\n", &students); 31 | printf("students = %p\n", students); 32 | printf("&students[0] = %p\n", &students[0]); 33 | 34 | Student * p = students; 35 | p[0].born = 2000; 36 | p[1].born = 2001; 37 | p[2].born = 2002; 38 | 39 | printf("students[0].born = %d\n", students[0].born); 40 | printf("students[1].born = %d\n", students[1].born); 41 | printf("students[2].born = %d\n", students[2].born); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /week05/examples/pointer-convert.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int * pi = new int[2](); 7 | unsigned char * pc = (unsigned char*)pi; 8 | pc[1] = 1; 9 | pc[5] = 2; 10 | cout << "pi[0] = " << pi[0] << endl; 11 | cout << "pi[1] = " << pi[1] << endl; 12 | 13 | delete []pi; 14 | //delete []pc; 15 | return 0; 16 | } -------------------------------------------------------------------------------- /week05/examples/pointer-pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int num = 10; 7 | int * p = # 8 | int ** pp = &p; 9 | *(*pp) = 20; 10 | 11 | cout << "num = " << num << endl; 12 | 13 | return 0; 14 | } -------------------------------------------------------------------------------- /week05/examples/pointer-struct.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Student 6 | { 7 | char name[4]; 8 | int born; 9 | bool male; 10 | }; 11 | 12 | int main() 13 | { 14 | Student stu = {"Yu", 2000, true}; 15 | Student * pStu = &stu; 16 | 17 | cout << stu.name << " was born in " << stu.born 18 | << ". Gender: " << (stu.male ? "male" : "female") << endl; 19 | 20 | strncpy(pStu->name, "Li", 4); 21 | pStu->born = 2001; 22 | (*pStu).born = 2002; 23 | pStu->male = false; 24 | 25 | cout << stu.name << " was born in " << stu.born 26 | << ". Gender: " << (stu.male ? "male" : "female") << endl; 27 | 28 | 29 | printf("Address of stu: %p\n", pStu); //C style 30 | cout << "Address of stu: " << pStu << endl; //C++ style 31 | cout << "Address of stu: " << &stu << endl; 32 | cout << "Address of member name: " << &(pStu->name) << endl; 33 | cout << "Address of member born: " << &(pStu->born) << endl; 34 | cout << "Address of member male: " << &(pStu->male) << endl; 35 | 36 | cout << "sizeof(pStu) = " << sizeof(pStu) << endl; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /week05/examples/pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int num = 10; 8 | int * p1 = NULL, * p2 = NULL; // declaration, initialize to 0 9 | p1 = # // take the address of num, assign to p1 10 | p2 = # // take the address of num, assign to p2 11 | 12 | cout << "num = " << num << endl; 13 | 14 | *p1 = 20; // assign to num 15 | cout << "num = " << num << endl; 16 | 17 | *p2 = 30; // assign to num 18 | cout << "num = " << num << endl; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /week05/examples/stack-heap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int a = 0; 7 | int b = 0; 8 | int c = 0; 9 | 10 | cout << &a << endl; 11 | cout << &b << endl; 12 | cout << &c << endl; 13 | 14 | int * p1 = (int*) malloc (4); 15 | int * p2 = (int*) malloc (4); 16 | int * p3 = (int*) malloc (4); 17 | 18 | cout << &p1 << endl; 19 | cout << &p2 << endl; 20 | cout << &p3 << endl; 21 | 22 | cout << p1 << endl; 23 | cout << p2 << endl; 24 | cout << p3 << endl; 25 | 26 | free(p1); 27 | free(p2); 28 | free(p3); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /week05/images/data-segments.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/images/data-segments.png -------------------------------------------------------------------------------- /week05/images/pointer-arithmetic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/images/pointer-arithmetic.png -------------------------------------------------------------------------------- /week05/images/pointer-array-elements.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/images/pointer-array-elements.png -------------------------------------------------------------------------------- /week05/images/pointer-pointer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/images/pointer-pointer.png -------------------------------------------------------------------------------- /week05/images/pointer-struct.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/images/pointer-struct.png -------------------------------------------------------------------------------- /week05/images/pointer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week05/images/pointer.png -------------------------------------------------------------------------------- /week06/Lab06.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week06/Lab06.pdf -------------------------------------------------------------------------------- /week06/Lab06.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week06/Lab06.pptx -------------------------------------------------------------------------------- /week06/Lecture06.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week06/Lecture06.pdf -------------------------------------------------------------------------------- /week06/Lecture06.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week06/Lecture06.pptx -------------------------------------------------------------------------------- /week06/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 6: Basics of Functions 2 | 3 | ## Function arguments (pass by value) 4 | 5 | ## array and pointer arguments 6 | 7 | ## C style array strings 8 | 9 | ## struct arguments (copy data or address) 10 | 11 | ## Reference and const 12 | 13 | ## inline function (why inline? Comparison with macro) 14 | 15 | ## Lab: 16 | 17 | * an example to test integer arguments, pointer argument and reference arguments 18 | -------------------------------------------------------------------------------- /week06/examples/function.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Matrix 5 | { 6 | size_t rows; 7 | size_t cols; 8 | float * pData; 9 | }; 10 | 11 | float matrix_max(struct Matrix mat) 12 | { 13 | float max = FLT_MIN; 14 | //find max value of mat 15 | for(size_t r = 0; r < mat.rows; r++) 16 | for (size_t c = 0; c < mat.cols; c++) 17 | { 18 | float val = mat.pData[ r * mat.cols + c]; 19 | max = ( max > val ? max : val); 20 | } 21 | return max; 22 | } 23 | 24 | Matrix * create_matrix(size_t rows, size_t cols) 25 | { 26 | Matrix * p = new Matrix{rows, cols}; 27 | p->pData = new float[p->rows * p->cols]{1.f, 2.f, 3.f}; 28 | //you should check if the memory is allocated successfully 29 | return p; 30 | } 31 | 32 | bool matrix_add(const Matrix & matA, const Matrix & matB, Matrix & matC) 33 | { 34 | // check the dimensions of the three matrices 35 | // re-create matC if needed 36 | // do: matC = matA + matB 37 | // return true if everything is right 38 | return true; 39 | } 40 | 41 | int main() 42 | { 43 | using namespace std; 44 | 45 | Matrix matA = {3,4}; 46 | matA.pData = new float[matA.rows * matA.cols]{1.f, 2.f, 3.f}; 47 | 48 | Matrix matB = {4,8}; 49 | matB.pData = new float[matB.rows * matB.cols]{10.f, 20.f, 30.f}; 50 | 51 | Matrix matC = {4, 2}; 52 | matC.pData = new float[matC.rows * matC.cols]{100.f, 200.f, 300.f}; 53 | 54 | // some operations on the matrices 55 | 56 | float maxa = matrix_max(matA); 57 | float maxb = matrix_max(matB); 58 | float maxc = matrix_max(matC); 59 | 60 | cout << "max(matA) = " << maxa << endl; 61 | cout << "max(matB) = " << maxb << endl; 62 | cout << "max(matC) = " << maxc << endl; 63 | 64 | 65 | delete [] matA.pData; 66 | delete [] matB.pData; 67 | delete [] matC.pData; 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /week06/examples/inline.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | inline float max_function(float a, float b) 5 | { 6 | if (a > b) 7 | return a; 8 | else 9 | return b; 10 | } 11 | 12 | //#define MAX_MACRO(a, b) a>b ? a : b 13 | 14 | #define MAX_MACRO(a, b) (a)>(b) ? (a) : (b) 15 | 16 | int main() 17 | { 18 | int num1 = 20; 19 | int num2 = 30; 20 | int maxv = max_function(num1, num2); 21 | cout << maxv << endl; 22 | 23 | maxv = MAX_MACRO(num1, num2); 24 | cout << maxv << endl; 25 | 26 | maxv = MAX_MACRO(num1++, num2++); 27 | cout << maxv << endl; 28 | cout << "num1=" << num1 << endl; 29 | cout << "num2=" << num2 << endl; 30 | 31 | num1 = 0xAB09; 32 | num2 = 0xEF08; 33 | maxv = MAX_MACRO(num1&0xFF, num2&0xFF); 34 | cout << maxv << endl; 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /week06/examples/lab/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // main.cpp 3 | #include 4 | #include "mymath.h" 5 | int main() 6 | { 7 | float arr1[8]{1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}; 8 | float * arr2 = NULL; 9 | 10 | float sum1 = arraySum(arr1, 8); 11 | float sum2 = arraySum(arr2, 8); 12 | 13 | std::cout << "The result1 is " << sum1 << std::endl; 14 | std::cout << "The result2 is " << sum2 << std::endl; 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /week06/examples/lab/mymath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mymath.h" 3 | 4 | float arraySum(const float *array, size_t size) 5 | { 6 | if(array == NULL) 7 | { 8 | std::cerr << "NULL pointer!" << std::endl; 9 | return 0.0f; 10 | } 11 | float sum = 0.0f; 12 | for(size_t i = 0; i < size; i++) 13 | sum += array[i]; 14 | return sum; 15 | } 16 | -------------------------------------------------------------------------------- /week06/examples/lab/mymath.h: -------------------------------------------------------------------------------- 1 | #ifndef __MY_MATH_H__ 2 | #define __MY_MATH_H__ 3 | float arraySum(const float *array, size_t size); 4 | #endif 5 | -------------------------------------------------------------------------------- /week06/examples/nofunction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Matrix 5 | { 6 | size_t rows; 7 | size_t cols; 8 | float * pData; 9 | }; 10 | 11 | int main() 12 | { 13 | using namespace std; 14 | 15 | Matrix matA = {3,4}; 16 | matA.pData = new float[matA.rows * matA.cols]{1.f, 2.f, 3.f}; 17 | 18 | Matrix matB = {4,8}; 19 | matB.pData = new float[matB.rows * matB.cols]{10.f, 20.f, 30.f}; 20 | 21 | Matrix matC = {4, 2}; 22 | matC.pData = new float[matC.rows * matC.cols]{100.f, 200.f, 300.f}; 23 | 24 | // some operations on the matrices 25 | 26 | float maxa = FLT_MIN; 27 | float maxb = FLT_MIN; 28 | float maxc = FLT_MIN; 29 | 30 | //find max value of matA 31 | for(size_t r = 0; r < matA.rows; r++) 32 | for (size_t c = 0; c < matA.cols; c++) 33 | { 34 | float val = matA.pData[ r * matA.cols + c]; 35 | maxa = ( maxa > val ? maxa : val); 36 | } 37 | 38 | //find max value of matB 39 | 40 | 41 | //find max value of matC 42 | 43 | cout << "max(matA) = " << maxa << endl; 44 | cout << "max(matB) = " << maxb << endl; 45 | cout << "max(matC) = " << maxc << endl; 46 | 47 | 48 | delete [] matA.pData; 49 | delete [] matB.pData; 50 | delete [] matC.pData; 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /week06/examples/param-pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int foo1(int x) 5 | { 6 | x += 10; 7 | return x; 8 | } 9 | 10 | 11 | int foo2(int * p) 12 | { 13 | (*p) += 10; 14 | return *p; 15 | } 16 | 17 | int main() 18 | { 19 | int num1 = 20; 20 | int num2 = foo1(num1); 21 | cout << "num1=" << num1 << endl; 22 | cout << "num2=" << num2 << endl; 23 | 24 | int * p = &num1; 25 | int num3 = foo2( p ); 26 | cout << "num1=" << num1 << endl; 27 | cout << "*p=" << *p << endl; 28 | cout << "num3=" << num3 << endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /week06/examples/param-reference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Matrix 5 | { 6 | size_t rows; 7 | size_t cols; 8 | float * pData; 9 | }; 10 | 11 | float matrix_max(const struct Matrix & mat) 12 | { 13 | float max = FLT_MIN; 14 | //find max value of mat 15 | for(size_t r = 0; r < mat.rows; r++) 16 | for (size_t c = 0; c < mat.cols; c++) 17 | { 18 | float val = mat.pData[ r * mat.cols + c]; 19 | max = ( max > val ? max : val); 20 | } 21 | return max; 22 | } 23 | 24 | int main() 25 | { 26 | using namespace std; 27 | 28 | Matrix matA = {3,4}; 29 | matA.pData = new float[matA.rows * matA.cols]{1.f, 2.f, 3.f}; 30 | 31 | Matrix matB = {4,8}; 32 | matB.pData = new float[matB.rows * matB.cols]{10.f, 20.f, 30.f}; 33 | 34 | Matrix matC = {4, 2}; 35 | matC.pData = new float[matC.rows * matC.cols]{100.f, 200.f, 300.f}; 36 | 37 | // some operations on the matrices 38 | 39 | float maxa = matrix_max(matA); 40 | float maxb = matrix_max(matB); 41 | float maxc = matrix_max(matC); 42 | 43 | cout << "max(matA) = " << maxa << endl; 44 | cout << "max(matB) = " << maxb << endl; 45 | cout << "max(matC) = " << maxc << endl; 46 | 47 | 48 | delete [] matA.pData; 49 | delete [] matB.pData; 50 | delete [] matC.pData; 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /week06/examples/reference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int num = 0; 7 | int & num_ref = num; 8 | cout << "num = " << num << endl; 9 | 10 | num_ref = 10; 11 | cout << "num = " << num << endl; 12 | 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /week07/Lab07.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week07/Lab07.pdf -------------------------------------------------------------------------------- /week07/Lab07.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week07/Lab07.pptx -------------------------------------------------------------------------------- /week07/Lecture07.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week07/Lecture07.pdf -------------------------------------------------------------------------------- /week07/Lecture07.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week07/Lecture07.pptx -------------------------------------------------------------------------------- /week07/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 7: Advances in Functions 2 | 3 | ## Default arguments 4 | 5 | ## Function overloading 6 | 7 | ## Function templates 8 | 9 | ## Recursion 10 | 11 | ## Pointer to functions 12 | 13 | ## Lab: 14 | 15 | * implement a function with default arguments. 16 | * overload a function which can compute the absolute value for an array, the array can be int, float and double 17 | 18 | '''C++ 19 | vabs(int * p, int n); //should n be int or size_t, what's the difference, please create an arrary with more than 2^31 elements 20 | vabs(float * p, int n); 21 | vabs(float * p, int n); 22 | ''' -------------------------------------------------------------------------------- /week07/examples/default-argument.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | float norm(float x, float y, float z); 6 | float norm(float x, float y, float z = 0); 7 | float norm(float x, float y = 0, float z); 8 | 9 | int main() 10 | { 11 | cout << norm(3.0f) << endl; 12 | cout << norm(3.0f, 4.0f) << endl; 13 | cout << norm(3.0f, 4.0f, 5.0f) << endl; 14 | return 0; 15 | } 16 | 17 | float norm(float x, float y, float z) 18 | { 19 | return sqrt(x * x + y * y + z * z); 20 | } -------------------------------------------------------------------------------- /week07/examples/function-pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | float norm_l1(float x, float y); //declaration 6 | float norm_l2(float x, float y); //declaration 7 | float (*norm_ptr)(float x, float y); //norm_ptr is a function pointer 8 | 9 | int main() 10 | { 11 | norm_ptr = norm_l1; //Pointer norm_ptr is pointing to norm_l1 12 | cout << "L1 norm of (-3, 4) = " << norm_ptr(-3.0f, 4.0f) << endl; 13 | 14 | norm_ptr = &norm_l2; //Pointer norm_ptr is pointing to norm_l2 15 | cout << "L2 norm of (-3, 4) = " << (*norm_ptr)(-3.0f, 4.0f) << endl; 16 | 17 | return 0; 18 | } 19 | 20 | float norm_l1(float x, float y) 21 | { 22 | return fabs(x) + fabs(y); 23 | } 24 | 25 | float norm_l2(float x, float y) 26 | { 27 | return sqrt(x * x + y * y); 28 | } -------------------------------------------------------------------------------- /week07/examples/function-reference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | float norm_l1(float x, float y); //declaration 6 | float norm_l2(float x, float y); //declaration 7 | float (&norm_ref)(float x, float y) = norm_l1; //norm_ref is a function reference 8 | 9 | int main() 10 | { 11 | cout << "L1 norm of (-3, 4) = " << norm_ref(-3, 4) << endl; 12 | return 0; 13 | } 14 | 15 | float norm_l1(float x, float y) 16 | { 17 | return fabs(x) + fabs(y); 18 | } 19 | 20 | float norm_l2(float x, float y) 21 | { 22 | return sqrt(x * x + y * y); 23 | } -------------------------------------------------------------------------------- /week07/examples/lab/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // main.cpp 3 | #include 4 | #include "mymath.h" 5 | int main() 6 | { 7 | float arr1[8]{1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}; 8 | float * arr2 = NULL; 9 | 10 | float sum1 = arraySum(arr1, 8); 11 | float sum2 = arraySum(arr2, 8); 12 | 13 | std::cout << "The result1 is " << sum1 << std::endl; 14 | std::cout << "The result2 is " << sum2 << std::endl; 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /week07/examples/lab/mymath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mymath.h" 3 | 4 | float arraySum(const float *array, size_t size) 5 | { 6 | if(array == NULL) 7 | { 8 | std::cerr << "NULL pointer!" << std::endl; 9 | return 0.0f; 10 | } 11 | float sum = 0.0f; 12 | for(size_t i = 0; i < size; i++) 13 | sum += array[i]; 14 | return sum; 15 | } 16 | -------------------------------------------------------------------------------- /week07/examples/lab/mymath.h: -------------------------------------------------------------------------------- 1 | #ifndef __MY_MATH_H__ 2 | #define __MY_MATH_H__ 3 | float arraySum(const float *array, size_t size); 4 | #endif 5 | -------------------------------------------------------------------------------- /week07/examples/overload.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int sum(int x, int y) 6 | { 7 | cout << "sum(int, int) is called" << endl; 8 | return x + y; 9 | } 10 | float sum(float x, float y) 11 | { 12 | cout << "sum(float, float) is called" << endl; 13 | return x + y; 14 | } 15 | double sum(double x, double y) 16 | { 17 | cout << "sum(double, double) is called" << endl; 18 | return x + y; 19 | } 20 | 21 | // //Is the following definition correct? 22 | // double sum(int x, int y) 23 | // { 24 | // cout << "sum(int, int) is called" << endl; 25 | // return x + y; 26 | // } 27 | 28 | int main() 29 | { 30 | 31 | cout << "sum = " << sum(1, 2) << endl; 32 | cout << "sum = " << sum(1.1f, 2.2f) << endl; 33 | cout << "sum = " << sum(1.1, 2.2) << endl; 34 | 35 | //which function will be called? 36 | cout << "sum = " << sum(1, 2.2) << endl; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /week07/examples/recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void div2(double val); 5 | 6 | int main() 7 | { 8 | div2(1024.); // call the recursive function 9 | return 0; 10 | } 11 | 12 | void div2(double val) 13 | { 14 | 15 | cout << "Entering val = " << val << endl; 16 | if (val > 1.0) 17 | div2( val / 2); // function calls itself 18 | else 19 | cout << "--------------------------" << endl; 20 | 21 | cout << "Leaving val = " << val << endl; 22 | } 23 | -------------------------------------------------------------------------------- /week07/examples/specialization.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | T sum(T x, T y) 7 | { 8 | cout << "The input type is " << typeid(T).name() << endl; 9 | return x + y; 10 | } 11 | 12 | struct Point 13 | { 14 | int x; 15 | int y; 16 | }; 17 | 18 | // Specialization for Point + Point operation 19 | template<> 20 | Point sum(Point pt1, Point pt2) 21 | { 22 | cout << "The input type is " << typeid(pt1).name() << endl; 23 | Point pt; 24 | pt.x = pt1.x + pt2.x; 25 | pt.y = pt1.y + pt2.y; 26 | return pt; 27 | } 28 | 29 | 30 | int main() 31 | { 32 | //Explicit instantiated functions 33 | cout << "sum = " << sum(1, 2) << endl; 34 | cout << "sum = " << sum(1.1, 2.2) << endl; 35 | 36 | Point pt1 {1, 2}; 37 | Point pt2 {2, 3}; 38 | Point pt = sum(pt1, pt2); 39 | cout << "pt = (" << pt.x << ", " << pt.y << ")" << endl; 40 | return 0; 41 | } -------------------------------------------------------------------------------- /week07/examples/template1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | T sum(T x, T y) 7 | { 8 | cout << "The input type is " << typeid(T).name() << endl; 9 | return x + 10 | y; 11 | } 12 | // Explicitly instantiate 13 | template double sum(double, double); 14 | 15 | int main() 16 | { 17 | auto val = sum(4.1, 5.2); 18 | cout << val << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /week07/examples/template2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | template 6 | T sum(T x, T y) 7 | { 8 | cout << "The input type is " << typeid(T).name() << endl; 9 | return x + y; 10 | } 11 | 12 | int main() 13 | { 14 | // Implicitly instantiates sum(int, int) 15 | cout << "sum = " << sum(2.2f, 3.0f) << endl; 16 | // Implicitly instantiates sum(float, float) 17 | cout << "sum = " << sum(2.2f, 3.0f) << endl; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /week08/Lab08.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week08/Lab08.pdf -------------------------------------------------------------------------------- /week08/Lab08.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week08/Lab08.pptx -------------------------------------------------------------------------------- /week08/Lecture08-cuda.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week08/Lecture08-cuda.pptx -------------------------------------------------------------------------------- /week08/Lecture08.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week08/Lecture08.pdf -------------------------------------------------------------------------------- /week08/Lecture08.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week08/Lecture08.pptx -------------------------------------------------------------------------------- /week08/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Chapter 8: Speedup Your Program 3 | 4 | ## Compiler options (-O3 for GCC, -Wall, etc…) 5 | 6 | ## SIMD (SSE, AVX, NEON, RISC-V, Universal Intrinsics of OpenCV) 7 | 8 | ## OpenMP 9 | 10 | ## Memory Hierarchies and Speed 11 | 12 | ## Crop ROI from a 2D Matrix 13 | 14 | ## Intel, ARM and RISC-V Architechture 15 | 16 | ## Lab: 17 | 18 | Create two 1Mx1K float matrices matA and matB, compute matA + matB. 19 | 20 | * compute the result row by row and col by col, compare the performance difference 21 | * use -O3 to improve the speed 22 | * improve the speed using SIMD, will the speed be improved? Why? 23 | -------------------------------------------------------------------------------- /week08/examples/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | add_definitions(-DWITH_NEON) 4 | #add_definitions(-DWITH_AVX2) 5 | #add_definitions(-mavx2) 6 | 7 | set(CMAKE_CXX_STANDARD 11) 8 | 9 | project(dotp) 10 | 11 | ADD_EXECUTABLE(dotp main.cpp matoperation.cpp) 12 | 13 | find_package(OpenMP) 14 | if(OpenMP_CXX_FOUND) 15 | message("OpenMP found.") 16 | target_link_libraries(dotp PUBLIC OpenMP::OpenMP_CXX) 17 | endif() 18 | 19 | -------------------------------------------------------------------------------- /week08/examples/cuda/arrayadd.cu: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | __global__ void add(const float * input1, const float * input2, float * output, size_t len) 4 | { 5 | int i = blockDim.x * blockIdx.x + threadIdx.x; 6 | if(i < len) 7 | { 8 | printf("(%d, %d) working for element %d\n", blockDim.x, threadIdx.x, i); 9 | output[i] = input1[i] + input2[i]; 10 | } 11 | else 12 | { 13 | printf("(%d, %d) skipped element %d\n", blockDim.x, threadIdx.x, i); 14 | } 15 | 16 | } 17 | 18 | int main() 19 | { 20 | cudaError_t ecode = cudaSuccess; 21 | const size_t len = 8; 22 | float vec1[len]{0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f}; 23 | float vec2[len]{1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f}; 24 | float vec3[len]{}; 25 | 26 | float * cudaVec1 = NULL; 27 | float * cudaVec2 = NULL; 28 | float * cudaVec3 = NULL; 29 | 30 | 31 | if (cudaMalloc (&cudaVec1, sizeof(float) * len) != cudaSuccess 32 | || cudaMalloc (&cudaVec2, sizeof(float) * len) != cudaSuccess 33 | || cudaMalloc (&cudaVec3, sizeof(float) * len) != cudaSuccess) 34 | { 35 | fprintf(stderr, "Allocate device memory failed.\n"); 36 | return -1; 37 | } 38 | cudaMemcpy(cudaVec1, vec1, sizeof(float)*len, cudaMemcpyHostToDevice); 39 | cudaMemcpy(cudaVec2, vec2, sizeof(float)*len, cudaMemcpyHostToDevice); 40 | add<<<2,2>>>(cudaVec1, cudaVec2, cudaVec3, len); 41 | if ((ecode = cudaGetLastError()) != cudaSuccess) // check 42 | { 43 | fprintf(stderr, "CUDA Error: %s\n", cudaGetErrorString(ecode)); 44 | return false; 45 | } 46 | cudaMemcpy(vec3, cudaVec3, sizeof(float)*len, cudaMemcpyDeviceToHost); 47 | cudaDeviceSynchronize(); 48 | 49 | for(size_t i = 0; i < len; i++) 50 | printf("vec3[%zu] = %.1f\n", i, vec3[i]); 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /week08/examples/cuda/hellocuda.cu: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | __global__ void mykernel() 4 | { 5 | printf("Hello, CUDA. I'm Thread %d in Block %d. blockDim=%d.\n", 6 | threadIdx.x, blockIdx.x, blockDim.x); 7 | } 8 | 9 | int main() 10 | { 11 | cudaError_t ecode = cudaSuccess; 12 | mykernel<<<2,2>>>(); 13 | if ((ecode = cudaGetLastError()) != cudaSuccess) // check 14 | { 15 | fprintf(stderr, "CUDA Error: %s\n", cudaGetErrorString(ecode)); 16 | return false; 17 | } 18 | cudaDeviceSynchronize(); 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /week08/examples/lab-python/demo1.py: -------------------------------------------------------------------------------- 1 | def fib(n): # write Fibonacci series up to n 2 | a, b = 0, 1 3 | while a < n: 4 | print(a, end=' ') 5 | a, b = b, a+b 6 | 7 | if __name__ == "__main__": 8 | print("this is demo1.py") 9 | fib(10) -------------------------------------------------------------------------------- /week08/examples/lab-python/demo2.py: -------------------------------------------------------------------------------- 1 | import fibs 2 | if __name__ == "__main__": 3 | fibs.fib(10) 4 | print() 5 | result=fibs.fib2(3) 6 | print(result) -------------------------------------------------------------------------------- /week08/examples/lab-python/demo3.py: -------------------------------------------------------------------------------- 1 | from fibs import * 2 | if __name__ == "__main__": 3 | fib(10) 4 | print() 5 | result=fib2(3) 6 | print(result) -------------------------------------------------------------------------------- /week08/examples/lab-python/demo4.py: -------------------------------------------------------------------------------- 1 | import demo1 2 | 3 | if __name__ == "__main__": 4 | print("this is demo4.py") 5 | demo1.fib(2) -------------------------------------------------------------------------------- /week08/examples/lab-python/fibs.py: -------------------------------------------------------------------------------- 1 | def fib(n): # write Fibonacci series up to n 2 | a, b = 0, 1 3 | while a < n: 4 | print(a, end=' ') 5 | a, b = b, a+b 6 | 7 | def fib2(n): # return Fibonacci series up to n 8 | result = [] 9 | a, b = 0, 1 10 | while a < n: 11 | result.append(a) 12 | a, b = b, a+b 13 | return result 14 | -------------------------------------------------------------------------------- /week08/examples/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "matoperation.hpp" 5 | using namespace std; 6 | 7 | #define TIME_START start=std::chrono::steady_clock::now(); 8 | #define TIME_END(NAME) end=std::chrono::steady_clock::now(); \ 9 | duration=std::chrono::duration_cast(end-start).count();\ 10 | cout<<(NAME)<<": result="<(aligned_alloc(256, nSize*sizeof(float))); 23 | // float * p2 = static_cast(aligned_alloc(256, nSize*sizeof(float))); 24 | float result = 0.0f; 25 | 26 | p1[2] = 2.3f; 27 | p2[2] = 3.0f; 28 | p1[nSize-1] = 2.0f; 29 | p2[nSize-1] = 1.1f; 30 | 31 | auto start = std::chrono::steady_clock::now(); 32 | auto end = std::chrono::steady_clock::now(); 33 | auto duration = 0L; 34 | 35 | result = dotproduct(p1, p2, nSize); 36 | result = dotproduct(p1, p2, nSize); 37 | 38 | TIME_START 39 | result = dotproduct(p1, p2, nSize); 40 | TIME_END("normal") 41 | 42 | TIME_START 43 | result = dotproduct_unloop(p1, p2, nSize); 44 | TIME_END("unloop") 45 | 46 | TIME_START 47 | result = dotproduct_neon(p1, p2, nSize); 48 | TIME_END("SIMD") 49 | 50 | TIME_START 51 | result = dotproduct_neon_omp(p1, p2, nSize); 52 | TIME_END("SIMD+OpenMP") 53 | 54 | delete []p1; 55 | delete []p2; 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /week08/examples/matoperation.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | float dotproduct(const float *p1, const float * p2, size_t n); 5 | float dotproduct_unloop(const float *p1, const float * p2, size_t n); 6 | float dotproduct_avx2(const float *p1, const float * p2, size_t n); 7 | float dotproduct_avx2_omp(const float *p1, const float * p2, size_t n); 8 | float dotproduct_neon(const float *p1, const float * p2, size_t n); 9 | float dotproduct_neon_omp(const float *p1, const float * p2, size_t n); 10 | -------------------------------------------------------------------------------- /week09/Lab09.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week09/Lab09.pdf -------------------------------------------------------------------------------- /week09/Lab09.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week09/Lab09.pptx -------------------------------------------------------------------------------- /week09/Lecture09.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week09/Lecture09.pdf -------------------------------------------------------------------------------- /week09/Lecture09.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week09/Lecture09.pptx -------------------------------------------------------------------------------- /week09/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 9: Basics of Classes 2 | 3 | ## Class Definition 4 | 5 | * build-in types and user defined types 6 | * data component and method/functions 7 | * Access control: public and private 8 | * Put the source code into a header and a CPP 9 | 10 | ## Constructors and Destructors 11 | 12 | * Constructors 13 | * Default Constructors 14 | * Destructors 15 | * Initialization 16 | 17 | ## Using a Class 18 | * const member functions 19 | * const member variables 20 | * static member variables 21 | 22 | 23 | ## this pointer 24 | 25 | ## Lab 26 | 27 | Create a simple class. Please try to test: 28 | 29 | * access a private member 30 | * modify a const data member 31 | * modify a data member in a const function 32 | * initialize a const data member 33 | -------------------------------------------------------------------------------- /week09/examples/access-attribute.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Student 5 | { 6 | private: 7 | char name[4]; 8 | int born; 9 | bool male; 10 | public: 11 | void setName(const char * s) 12 | { 13 | if (s == NULL) 14 | { 15 | std::cerr << "The input is NULL." << std::endl; 16 | return; 17 | } 18 | size_t len = sizeof(name) - 1; 19 | strncpy(name, s, len); 20 | name[len] = '\0'; 21 | } 22 | void setBorn(int b) 23 | { 24 | if (b >= 1990 && b <= 2020 ) 25 | born = b; 26 | else 27 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 28 | } 29 | void setGender(bool isMale) 30 | { 31 | male = isMale; 32 | } 33 | void printInfo() 34 | { 35 | std::cout << "Name: " << name << std::endl; 36 | std::cout << "Born in " << born << std::endl; 37 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | Student yu; 44 | yu.setName("Yu"); 45 | yu.setBorn(2000); 46 | yu.setGender(true); 47 | yu.born = 2001; // you cannot access a private member 48 | yu.printInfo(); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /week09/examples/array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Student 7 | { 8 | private: 9 | char * name; 10 | int born; 11 | bool male; 12 | public: 13 | Student() 14 | { 15 | name = new char[1024]{0}; 16 | born = 0; 17 | male = false; 18 | cout << "Constructor: Person()" << endl; 19 | } 20 | Student(const char * initName, int initBorn, bool isMale) 21 | { 22 | name = new char[1024]; 23 | setName(initName); 24 | born = initBorn; 25 | male = isMale; 26 | cout << "Constructor: Person(const char, int , bool)" << endl; 27 | } 28 | ~Student() 29 | { 30 | cout << "To destroy object: " << name << endl; 31 | delete [] name; 32 | } 33 | 34 | void setName(const char * s) 35 | { 36 | if (s == NULL) 37 | { 38 | std::cerr << "The input is NULL." << std::endl; 39 | return; 40 | } 41 | size_t len = 1024 - 1; 42 | strncpy(name, s, len); 43 | name[len] = '\0'; 44 | } 45 | void setBorn(int b) 46 | { 47 | if (b >= 1990 && b <= 2020 ) 48 | born = b; 49 | else 50 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 51 | } 52 | // the declarations, the definitions are out of the class 53 | void setGender(bool isMale); 54 | void printInfo(); 55 | }; 56 | 57 | void Student::setGender(bool isMale) 58 | { 59 | male = isMale; 60 | } 61 | void Student::printInfo() 62 | { 63 | std::cout << "Name: " << name << std::endl; 64 | std::cout << "Born in " << born << std::endl; 65 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 66 | } 67 | 68 | int main() 69 | { 70 | Student * class1 = new Student[3]{ 71 | {"Tom", 2000, true}, 72 | {"Bob", 2001, true}, 73 | {"Amy", 2002, false}, 74 | }; 75 | 76 | class1[1].printInfo(); 77 | delete class1; 78 | //delete []class1; 79 | 80 | 81 | return 0; 82 | } -------------------------------------------------------------------------------- /week09/examples/const.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Student 7 | { 8 | private: 9 | const int BMI = 24; 10 | char * name; 11 | int born; 12 | bool male; 13 | public: 14 | Student() 15 | { 16 | name = new char[1024]{0}; 17 | born = 0; 18 | male = false; 19 | BMI = 25;//can it be modified? 20 | cout << "Constructor: Person()" << endl; 21 | } 22 | Student(const char * name, int born, bool male) 23 | { 24 | this->name = new char[1024]; 25 | setName(name); 26 | this->born = born; 27 | this->male = male; 28 | cout << "Constructor: Person(const char, int , bool)" << endl; 29 | } 30 | ~Student() 31 | { 32 | cout << "To destroy object: " << name << endl; 33 | delete [] name; 34 | } 35 | 36 | void setName(const char * s) 37 | { 38 | if (s == NULL) 39 | { 40 | std::cerr << "The input is NULL." << std::endl; 41 | return; 42 | } 43 | size_t len = 1024 - 1; 44 | strncpy(name, s, len); 45 | name[len] = '\0'; 46 | } 47 | void setBorn(int b) 48 | { 49 | if (b >= 1990 && b <= 2020 ) 50 | born = b; 51 | else 52 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 53 | } 54 | int getBorn() const 55 | { 56 | born++; //Can it be modified? 57 | return born; 58 | } 59 | // the declarations, the definitions are out of the class 60 | void setGender(bool isMale); 61 | void printInfo(); 62 | }; 63 | 64 | void Student::setGender(bool isMale) 65 | { 66 | male = isMale; 67 | } 68 | void Student::printInfo() 69 | { 70 | std::cout << "Name: " << name << std::endl; 71 | std::cout << "Born in " << born << std::endl; 72 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 73 | } 74 | 75 | int main() 76 | { 77 | Student yu("Yu", 2000, true); 78 | cout << "yu.getBorn() = " << yu.getBorn() << endl; 79 | return 0; 80 | } -------------------------------------------------------------------------------- /week09/examples/constructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Student 7 | { 8 | private: 9 | char name[4]; 10 | int born; 11 | bool male; 12 | public: 13 | Student() 14 | { 15 | name[0] = '\0'; 16 | born = 0; 17 | male = false; 18 | cout << "Constructor: Person()" << endl; 19 | } 20 | Student(const char * initName): born(0), male(false) 21 | { 22 | setName(initName); 23 | cout << "Constructor: Person(const char*)" << endl; 24 | } 25 | Student(const char * initName, int initBorn, bool isMale) 26 | { 27 | setName(initName); 28 | born = initBorn; 29 | male = isMale; 30 | cout << "Constructor: Person(const char, int , bool)" << endl; 31 | } 32 | 33 | void setName(const char * s) 34 | { 35 | if (s == NULL) 36 | { 37 | std::cerr << "The input is NULL." << std::endl; 38 | return; 39 | } 40 | size_t len = sizeof(name) - 1; 41 | strncpy(name, s, len); 42 | name[len] = '\0'; 43 | } 44 | void setBorn(int b) 45 | { 46 | if (b >= 1990 && b <= 2020 ) 47 | born = b; 48 | else 49 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 50 | } 51 | // the declarations, the definitions are out of the class 52 | void setGender(bool isMale); 53 | void printInfo(); 54 | }; 55 | 56 | void Student::setGender(bool isMale) 57 | { 58 | male = isMale; 59 | } 60 | void Student::printInfo() 61 | { 62 | std::cout << "Name: " << name << std::endl; 63 | std::cout << "Born in " << born << std::endl; 64 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 65 | } 66 | 67 | int main() 68 | { 69 | Student yu; 70 | yu.printInfo(); 71 | 72 | yu.setName("Yu"); 73 | yu.setBorn(2000); 74 | yu.setGender(true); 75 | yu.printInfo(); 76 | 77 | Student li("li"); 78 | li.printInfo(); 79 | 80 | Student xue = Student("XueQikun", 1962, true); 81 | //a question: what will happen since "XueQikun" has 4+ characters? 82 | xue.printInfo(); 83 | 84 | Student * zhou = new Student("Zhou", 1991, false); 85 | zhou->printInfo(); 86 | delete zhou; 87 | 88 | Student * s = new Student(); 89 | // Student * s = new Student; // the same 90 | s->printInfo(); 91 | delete s; 92 | 93 | return 0; 94 | } -------------------------------------------------------------------------------- /week09/examples/destructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Student 7 | { 8 | private: 9 | char * name; 10 | int born; 11 | bool male; 12 | public: 13 | Student() 14 | { 15 | name = new char[1024]{0}; 16 | born = 0; 17 | male = false; 18 | cout << "Constructor: Person()" << endl; 19 | } 20 | Student(const char * initName, int initBorn, bool isMale) 21 | { 22 | name = new char[1024]; 23 | setName(initName); 24 | born = initBorn; 25 | male = isMale; 26 | cout << "Constructor: Person(const char, int , bool)" << endl; 27 | } 28 | ~Student() 29 | { 30 | cout << "To destroy object: " << name << endl; 31 | delete [] name; 32 | } 33 | 34 | void setName(const char * s) 35 | { 36 | if (s == NULL) 37 | { 38 | std::cerr << "The input is NULL." << std::endl; 39 | return; 40 | } 41 | size_t len = 1024 - 1; 42 | strncpy(name, s, len); 43 | name[len] = '\0'; 44 | } 45 | void setBorn(int b) 46 | { 47 | if (b >= 1990 && b <= 2020 ) 48 | born = b; 49 | else 50 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 51 | } 52 | // the declarations, the definitions are out of the class 53 | void setGender(bool isMale); 54 | void printInfo(); 55 | }; 56 | 57 | void Student::setGender(bool isMale) 58 | { 59 | male = isMale; 60 | } 61 | void Student::printInfo() 62 | { 63 | std::cout << "Name: " << name << std::endl; 64 | std::cout << "Born in " << born << std::endl; 65 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 66 | } 67 | 68 | int main() 69 | { 70 | { 71 | Student yu; 72 | yu.printInfo(); 73 | 74 | yu.setName("Yu"); 75 | yu.setBorn(2000); 76 | yu.setGender(true); 77 | yu.printInfo(); 78 | } 79 | Student xue = Student("XueQikun", 1962, true); 80 | xue.printInfo(); 81 | 82 | Student * zhou = new Student("Zhou", 1991, false); 83 | zhou->printInfo(); 84 | delete zhou; 85 | 86 | return 0; 87 | } -------------------------------------------------------------------------------- /week09/examples/firstclass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Student 5 | { 6 | public: 7 | char name[4]; 8 | int born; 9 | bool male; 10 | void setName(const char * s) 11 | { 12 | if (s == NULL) 13 | { 14 | std::cerr << "The input is NULL." << std::endl; 15 | return; 16 | } 17 | size_t len = sizeof(name) - 1; 18 | strncpy(name, s, len); 19 | name[len] = '\0'; 20 | } 21 | void setBorn(int b) 22 | { 23 | if (b >= 1990 && b <= 2020 ) 24 | born = b; 25 | else 26 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 27 | } 28 | void setGender(bool isMale) 29 | { 30 | male = isMale; 31 | } 32 | void printInfo() 33 | { 34 | std::cout << "Name: " << name << std::endl; 35 | std::cout << "Born in " << born << std::endl; 36 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 37 | } 38 | }; 39 | 40 | int main() 41 | { 42 | Student yu; 43 | yu.setName("Yu"); 44 | yu.setBorn(2000); 45 | yu.setGender(true); 46 | yu.born = 2001; // it can also be manipulated directly 47 | yu.printInfo(); 48 | std::cout << "It's name is " << yu.name << std::endl; 49 | return 0; 50 | } -------------------------------------------------------------------------------- /week09/examples/function.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Student 5 | { 6 | private: 7 | char name[4]; 8 | int born; 9 | bool male; 10 | public: 11 | void setName(const char * s) 12 | { 13 | if (s == NULL) 14 | { 15 | std::cerr << "The input is NULL." << std::endl; 16 | return; 17 | } 18 | size_t len = sizeof(name) - 1; 19 | strncpy(name, s, len); 20 | name[len] = '\0'; 21 | } 22 | void setBorn(int b) 23 | { 24 | if (b >= 1990 && b <= 2020 ) 25 | born = b; 26 | else 27 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 28 | } 29 | // the declarations, the definitions are out of the class 30 | void setGender(bool isMale); 31 | void printInfo(); 32 | }; 33 | 34 | void Student::setGender(bool isMale) 35 | { 36 | male = isMale; 37 | } 38 | void Student::printInfo() 39 | { 40 | std::cout << "Name: " << name << std::endl; 41 | std::cout << "Born in " << born << std::endl; 42 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 43 | } 44 | 45 | int main() 46 | { 47 | Student yu; 48 | yu.setName("Yu"); 49 | yu.setBorn(2000); 50 | yu.setGender(true); 51 | yu.printInfo(); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /week09/examples/multi-files/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | project(persondemo) 4 | 5 | ADD_EXECUTABLE(persondemo main.cpp student.cpp) 6 | 7 | -------------------------------------------------------------------------------- /week09/examples/multi-files/main.cpp: -------------------------------------------------------------------------------- 1 | #include "student.hpp" 2 | 3 | int main() 4 | { 5 | Student yu; 6 | yu.setName("Yu"); 7 | yu.setBorn(2000); 8 | yu.setGender(true); 9 | yu.printInfo(); 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /week09/examples/multi-files/student.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "student.hpp" 3 | 4 | void Student::setGender(bool isMale) 5 | { 6 | male = isMale; 7 | } 8 | void Student::printInfo() 9 | { 10 | std::cout << "Name: " << name << std::endl; 11 | std::cout << "Born in " << born << std::endl; 12 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 13 | } 14 | -------------------------------------------------------------------------------- /week09/examples/multi-files/student.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | class Student 5 | { 6 | private: 7 | char name[4]; 8 | int born; 9 | bool male; 10 | public: 11 | void setName(const char * s) 12 | { 13 | if (s == NULL) 14 | { 15 | std::cerr << "The input is NULL." << std::endl; 16 | return; 17 | } 18 | size_t len = sizeof(name) - 1; 19 | strncpy(name, s, len); 20 | name[len] = '\0'; 21 | } 22 | void setBorn(int b) 23 | { 24 | if (b >= 1990 && b <= 2020 ) 25 | born = b; 26 | else 27 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 28 | } 29 | // the declarations, the definitions are out of the class 30 | void setGender(bool isMale); 31 | void printInfo(); 32 | }; 33 | -------------------------------------------------------------------------------- /week09/examples/this.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Student 7 | { 8 | private: 9 | char * name; 10 | int born; 11 | bool male; 12 | public: 13 | Student() 14 | { 15 | name = new char[1024]{0}; 16 | born = 0; 17 | male = false; 18 | cout << "Constructor: Person()" << endl; 19 | } 20 | Student(const char * initName, int initBorn, bool isMale) 21 | { 22 | name = new char[1024]; 23 | setName(initName); 24 | born = initBorn; 25 | male = isMale; 26 | cout << "Constructor: Person(const char, int , bool)" << endl; 27 | cout << "this = " << static_cast(this) << endl; 28 | } 29 | ~Student() 30 | { 31 | cout << "To destroy object: " << name << endl; 32 | delete [] name; 33 | } 34 | 35 | void setName(const char * s) 36 | { 37 | if (s == NULL) 38 | { 39 | std::cerr << "The input is NULL." << std::endl; 40 | return; 41 | } 42 | size_t len = 1024 - 1; 43 | strncpy(name, s, len); 44 | name[len] = '\0'; 45 | } 46 | void setBorn(int b) 47 | { 48 | if (b >= 1990 && b <= 2020 ) 49 | born = b; 50 | else 51 | std::cerr << "The input b is " << b << ", and should be in [1990, 2020]." << std::endl; 52 | } 53 | // the declarations, the definitions are out of the class 54 | void setGender(bool isMale); 55 | void printInfo(); 56 | }; 57 | 58 | void Student::setGender(bool isMale) 59 | { 60 | male = isMale; 61 | } 62 | void Student::printInfo() 63 | { 64 | std::cout << "Name: " << name << std::endl; 65 | std::cout << "Born in " << born << std::endl; 66 | std::cout << "Gender: " << (male ? "Male" : "Female") << std::endl; 67 | } 68 | 69 | int main() 70 | { 71 | Student * s = new Student("Tom", 2000, true); 72 | cout << "s = " << static_cast(s) << endl; 73 | return 0; 74 | } -------------------------------------------------------------------------------- /week10/Lab10.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week10/Lab10.pdf -------------------------------------------------------------------------------- /week10/Lab10.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week10/Lab10.pptx -------------------------------------------------------------------------------- /week10/Lecture10.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week10/Lecture10.pdf -------------------------------------------------------------------------------- /week10/Lecture10.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week10/Lecture10.pptx -------------------------------------------------------------------------------- /week10/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 10: Advances in Classes 2 | 3 | ## operator overloading 4 | 5 | ## friend Functions and << operator 6 | 7 | ## Automatic Conversions and Type Casts for Classes 8 | 9 | ## Lab 10 | 11 | overload + and << for your own defined class 12 | -------------------------------------------------------------------------------- /week10/examples/example1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "time.hpp" 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | MyTime t1(2, 40); 9 | MyTime t2(1, 20); 10 | std::cout << (t1 + t2).getTime() << std::endl; 11 | 12 | t1 += t2; //operator 13 | t1.operator+=(t2); //function 14 | 15 | std::cout << t1.getTime() << endl; 16 | 17 | return 0; 18 | } 19 | 20 | -------------------------------------------------------------------------------- /week10/examples/example1/time.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyTime 5 | { 6 | int hours; 7 | int minutes; 8 | public: 9 | MyTime(): hours(0), minutes(0){} 10 | MyTime(int h, int m): hours(h), minutes(m){} 11 | 12 | MyTime operator+(const MyTime & t) const 13 | { 14 | MyTime sum; 15 | sum.minutes = this->minutes + t.minutes; 16 | sum.hours = this->hours + t.hours; 17 | 18 | sum.hours += sum.minutes / 60; 19 | sum.minutes %= 60; 20 | 21 | return sum; 22 | } 23 | MyTime & operator+=(const MyTime & t) 24 | { 25 | this->minutes += t.minutes; 26 | this->hours += t.hours; 27 | 28 | this->hours += this->minutes / 60; 29 | this->minutes %= 60; 30 | 31 | return *this; 32 | } 33 | std::string getTime() const 34 | { 35 | return std::to_string(this->hours) + " hours and " 36 | + std::to_string(this->minutes) + " minutes."; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /week10/examples/example2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "time.hpp" 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | MyTime t1(2, 40); 9 | std::cout << (t1 + 30).getTime() << std::endl; 10 | 11 | t1 += 30; //operator 12 | t1.operator+=(30); //function 13 | 14 | std::cout << t1.getTime() << endl; 15 | 16 | std::cout << (t1 + "one hour").getTime() << std::endl; 17 | std::cout << (t1 + "two hour").getTime() << std::endl; 18 | 19 | return 0; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /week10/examples/example2/time.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyTime 5 | { 6 | int hours; 7 | int minutes; 8 | public: 9 | MyTime(): hours(0), minutes(0){} 10 | MyTime(int h, int m): hours(h), minutes(m){} 11 | 12 | MyTime operator+(const MyTime & t) const 13 | { 14 | MyTime sum; 15 | sum.minutes = this->minutes + t.minutes; 16 | sum.hours = this->hours + t.hours; 17 | 18 | sum.hours += sum.minutes / 60; 19 | sum.minutes %= 60; 20 | 21 | return sum; 22 | } 23 | MyTime & operator+=(const MyTime & t) 24 | { 25 | this->minutes += t.minutes; 26 | this->hours += t.hours; 27 | 28 | this->hours += this->minutes / 60; 29 | this->minutes %= 60; 30 | 31 | return *this; 32 | } 33 | 34 | MyTime operator+(int m) const 35 | { 36 | MyTime sum; 37 | sum.minutes = this->minutes + m; 38 | sum.hours = this->hours; 39 | sum.hours += sum.minutes / 60; 40 | sum.minutes %= 60; 41 | return sum; 42 | } 43 | MyTime & operator+=(int m) 44 | { 45 | this->minutes += m; 46 | this->hours += this->minutes / 60; 47 | this->minutes %= 60; 48 | return *this; 49 | } 50 | 51 | MyTime operator+(const std::string str) const 52 | { 53 | MyTime sum = *this; 54 | if(str=="one hour") 55 | sum.hours = this->hours + 1; 56 | else 57 | std::cerr<< "Only \"one hour\" is supported." << std::endl; 58 | return sum; 59 | } 60 | 61 | std::string getTime() const 62 | { 63 | return std::to_string(this->hours) + " hours and " 64 | + std::to_string(this->minutes) + " minutes."; 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /week10/examples/example3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "time.hpp" 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | MyTime t1(2, 40); 9 | std::cout << (30 + t1).getTime() << std::endl; 10 | 11 | std::cout << t1 << std::endl; 12 | std::cout << "Please input two integers:" << std::endl; 13 | std::cin >> t1; 14 | std::cout << t1 << std::endl; 15 | 16 | return 0; 17 | } 18 | 19 | -------------------------------------------------------------------------------- /week10/examples/example3/time.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyTime 5 | { 6 | int hours; 7 | int minutes; 8 | public: 9 | MyTime(): hours(0), minutes(0){} 10 | MyTime(int h, int m): hours(h), minutes(m){} 11 | 12 | MyTime operator+(const MyTime & t) const 13 | { 14 | MyTime sum; 15 | sum.minutes = this->minutes + t.minutes; 16 | sum.hours = this->hours + t.hours; 17 | 18 | sum.hours += sum.minutes / 60; 19 | sum.minutes %= 60; 20 | 21 | return sum; 22 | } 23 | MyTime & operator+=(const MyTime & t) 24 | { 25 | this->minutes += t.minutes; 26 | this->hours += t.hours; 27 | 28 | this->hours += this->minutes / 60; 29 | this->minutes %= 60; 30 | 31 | return *this; 32 | } 33 | 34 | MyTime operator+(int m) const 35 | { 36 | MyTime sum; 37 | sum.minutes = this->minutes + m; 38 | sum.hours = this->hours; 39 | sum.hours += sum.minutes / 60; 40 | sum.minutes %= 60; 41 | return sum; 42 | } 43 | 44 | friend MyTime operator+(int m, const MyTime & t) 45 | { 46 | return t + m; 47 | } 48 | 49 | std::string getTime() const 50 | { 51 | return std::to_string(this->hours) + " hours and " 52 | + std::to_string(this->minutes) + " minutes."; 53 | } 54 | 55 | friend std::ostream & operator<<(std::ostream & os, const MyTime & t) 56 | { 57 | std::string str = std::to_string(t.hours) + " hours and " 58 | + std::to_string(t.minutes) + " minutes."; 59 | os << str; 60 | return os; 61 | } 62 | friend std::istream & operator>>(std::istream & is, MyTime & t) 63 | { 64 | is >> t.hours >> t.minutes; 65 | t.hours += t.minutes / 60; 66 | t.minutes %= 60; 67 | return is; 68 | } 69 | }; 70 | -------------------------------------------------------------------------------- /week10/examples/example4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "time.hpp" 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | MyTime t1(1, 20); 9 | int minutes = t1; //implicit conversion 10 | float f = float(t1); //explicit conversion. 11 | std::cout << "minutes = " << minutes << std::endl; 12 | std::cout << "minutes = " << f << std::endl; 13 | 14 | MyTime t2 = 70; 15 | std::cout << "t2 is " << t2 << std::endl; 16 | 17 | MyTime t3; 18 | t3 = 80; 19 | std::cout << "t3 is " << t3 << std::endl; 20 | 21 | return 0; 22 | 23 | } 24 | 25 | -------------------------------------------------------------------------------- /week10/examples/example4/time.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyTime 5 | { 6 | int hours; 7 | int minutes; 8 | public: 9 | MyTime(): hours(0), minutes(0) 10 | { 11 | std::cout << "Constructor MyTime()" << std::endl; 12 | } 13 | MyTime(int m): hours(0), minutes(m) 14 | { 15 | std::cout << "Constructor MyTime(int)" << std::endl; 16 | this->hours += this->minutes / 60; 17 | this->minutes %= 60; 18 | } 19 | MyTime(int h, int m): hours(h), minutes(m) 20 | { 21 | std::cout << "Constructor MyTime(int,int)" << std::endl; 22 | } 23 | 24 | //implicit conversion 25 | operator int() const 26 | { 27 | std::cout << "operator int()" << std::endl; 28 | return this->hours * 60 + this->minutes; 29 | } 30 | //explicit conversion 31 | explicit operator float() const 32 | { 33 | std::cout << "explicit operator float()" << std::endl; 34 | return float(this->hours * 60 + this->minutes); 35 | } 36 | 37 | MyTime & operator=(int m) 38 | { 39 | std::cout << "operator=(int)" << std::endl; 40 | this->hours = 0; 41 | this->minutes = m; 42 | this->hours = this->minutes / 60; 43 | this->minutes %= 60; 44 | return *this; 45 | } 46 | 47 | friend std::ostream & operator<<(std::ostream & os, const MyTime & t) 48 | { 49 | std::string str = std::to_string(t.hours) + " hours and " 50 | + std::to_string(t.minutes) + " minutes."; 51 | os << str; 52 | return os; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /week10/examples/example5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "time.hpp" 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | MyTime t1(1, 59); 9 | MyTime t2 = t1++; 10 | MyTime t3 = ++t1; 11 | 12 | std::cout << "t1 is " << t1 << std::endl; 13 | std::cout << "t2 is " << t2 << std::endl; 14 | std::cout << "t3 is " << t3 << std::endl; 15 | 16 | return 0; 17 | 18 | } 19 | 20 | -------------------------------------------------------------------------------- /week10/examples/example5/time.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyTime 5 | { 6 | int hours; 7 | int minutes; 8 | public: 9 | MyTime(): hours(0), minutes(0) 10 | { 11 | std::cout << "Constructor MyTime()" << std::endl; 12 | } 13 | MyTime(int m): hours(0), minutes(m) 14 | { 15 | std::cout << "Constructor MyTime(int)" << std::endl; 16 | this->hours += this->minutes / 60; 17 | this->minutes %= 60; 18 | } 19 | MyTime(int h, int m): hours(h), minutes(m) 20 | { 21 | std::cout << "Constructor MyTime(int,int)" << std::endl; 22 | } 23 | MyTime & operator=(int m) 24 | { 25 | std::cout << "operator=(int)" << std::endl; 26 | this->hours = 0; 27 | this->minutes = m; 28 | this->hours = this->minutes / 60; 29 | this->minutes %= 60; 30 | return *this; 31 | } 32 | // prefix increment 33 | MyTime& operator++() 34 | { 35 | this->minutes++; 36 | this->hours += this->minutes / 60; 37 | this->minutes = this->minutes % 60; 38 | return *this; 39 | } 40 | 41 | // postfix increment 42 | MyTime operator++(int) 43 | { 44 | MyTime old = *this; // keep the old value 45 | operator++(); // prefix increment 46 | return old; 47 | } 48 | 49 | friend std::ostream & operator<<(std::ostream & os, const MyTime & t) 50 | { 51 | std::string str = std::to_string(t.hours) + " hours and " 52 | + std::to_string(t.minutes) + " minutes."; 53 | os << str; 54 | return os; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /week10/examples/exampleMat/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.5) 2 | set (CMAKE_CXX_STANDARD 11) 3 | 4 | project(matexample) 5 | 6 | find_package(OpenCV REQUIRED) 7 | message(STATUS "OpenCV library status:") 8 | message(STATUS " config: ${OpenCV_DIR}") 9 | message(STATUS " version: ${OpenCV_VERSION}") 10 | message(STATUS " libraries: ${OpenCV_LIBS}") 11 | message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}") 12 | 13 | include_directories( ${OpenCV_INCLUDE_DIRS} ) 14 | 15 | # Declare the executable target built from your sources 16 | add_executable(matexample matexample.cpp) 17 | 18 | # Link your application with OpenCV libraries 19 | target_link_libraries(matexample PRIVATE ${OpenCV_LIBS}) 20 | -------------------------------------------------------------------------------- /week10/examples/exampleMat/matexample.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | float a[6]={1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f}; 9 | float b[6]={1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; 10 | cv::Mat A(2, 3, CV_32FC1, a); 11 | cv::Mat B(3, 2, CV_32FC1, b); 12 | 13 | cv::Mat C = A * B; 14 | 15 | cout << "Matrix C = " << endl 16 | << C << endl; 17 | return 0; 18 | } -------------------------------------------------------------------------------- /week10/examples/stringdemo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | std::string s("Hello "); 7 | s += "C"; 8 | s.operator+=(" and CPP!"); 9 | 10 | std::cout << s << std::endl; 11 | return 0; 12 | } -------------------------------------------------------------------------------- /week11/Lab11.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week11/Lab11.pdf -------------------------------------------------------------------------------- /week11/Lab11.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week11/Lab11.pptx -------------------------------------------------------------------------------- /week11/Lecture11.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week11/Lecture11.pdf -------------------------------------------------------------------------------- /week11/Lecture11.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week11/Lecture11.pptx -------------------------------------------------------------------------------- /week11/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 11: Dynamic Memory Management in Classes 2 | 3 | ## Some Default Operations 4 | 5 | * Default constructor 6 | * Default copy constructor 7 | * Default copy assignment 8 | * How pointer members work by default 9 | 10 | ## An Example with Dynamic Data Allocation 11 | 12 | ## Solution 13 | 14 | ## Matrix Data Management in OpenCV 15 | 16 | ## Smart Pointers 17 | 18 | * std::unique_ptr (C++11) 19 | * std::shared_ptr (C++11) 20 | 21 | ## Lab 22 | 23 | Create a class for matrices which elements are in float. The class should support the follow operations and has no memory management problem. When a matrix is assigned to another by =, the two matrices will share the same data. 24 | `class Matrix{...};` 25 | `Matrix a(3,4);` 26 | `Matrix b(3,4);` 27 | `Matrix c = a + b;` 28 | `Matrix d = a * 2.0f;` 29 | -------------------------------------------------------------------------------- /week11/examples/example1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mystring.hpp" 3 | 4 | using namespace std; 5 | 6 | // Why memory leak and memory double free? 7 | int main() 8 | { 9 | { 10 | MyString str1(10, "Shenzhen"); 11 | cout << "str1: " << str1 << endl; 12 | 13 | MyString str2 = str1; 14 | cout << "str2: " << str2 << endl; 15 | 16 | MyString str3; 17 | cout << "str3: " << str3 << endl; 18 | str3 = str1; 19 | cout << "str3: " << str3 << endl; 20 | } 21 | cout << "end of main()" << endl; // it will not be printed out 22 | return 0; 23 | } -------------------------------------------------------------------------------- /week11/examples/example1/mystring.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | class MyString 7 | { 8 | private: 9 | int buf_len; 10 | char * characters; 11 | public: 12 | MyString(int buf_len = 64, const char * data = NULL) 13 | { 14 | std::cout << "Constructor(int, char*)" << std::endl; 15 | this->buf_len = 0; 16 | this->characters = NULL; 17 | create(buf_len, data); 18 | } 19 | ~MyString() 20 | { 21 | delete []this->characters; 22 | } 23 | bool create(int buf_len, const char * data) 24 | { 25 | this->buf_len = buf_len; 26 | 27 | if( this->buf_len != 0) 28 | { 29 | this->characters = new char[this->buf_len]{}; 30 | if(data) 31 | strncpy(this->characters, data, this->buf_len); 32 | } 33 | 34 | return true; 35 | } 36 | friend std::ostream & operator<<(std::ostream & os, const MyString & ms) 37 | { 38 | os << "buf_len = " << ms.buf_len; 39 | os << ", characters = " << static_cast(ms.characters); 40 | os << " [" << ms.characters << "]"; 41 | return os; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /week11/examples/example2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mystring.hpp" 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | { 9 | MyString str1(10, "Shenzhen"); 10 | cout << "str1: " << str1 << endl; 11 | 12 | MyString str2 = str1; 13 | cout << "str2: " << str2 << endl; 14 | 15 | MyString str3; 16 | cout << "str3: " << str3 << endl; 17 | str3 = str1; 18 | cout << "str3: " << str3 << endl; 19 | } 20 | cout << "end of main()" << endl; // it can be printed out 21 | return 0; 22 | } -------------------------------------------------------------------------------- /week11/examples/example2/mystring.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class MyString 6 | { 7 | private: 8 | int buf_len; 9 | char * characters; 10 | public: 11 | MyString(int buf_len = 64, const char * data = NULL) 12 | { 13 | std::cout << "Constructor(int, char*)" << std::endl; 14 | this->buf_len = 0; 15 | this->characters = NULL; 16 | create(buf_len, data); 17 | } 18 | MyString(const MyString & ms) 19 | { 20 | std::cout << "Constructor(MyString&)" << std::endl; 21 | this->buf_len = 0; 22 | this->characters = NULL; 23 | create(ms.buf_len, ms.characters); 24 | } 25 | ~MyString() 26 | { 27 | release(); 28 | } 29 | MyString & operator=(const MyString &ms) 30 | { 31 | create(ms.buf_len, ms.characters); 32 | return *this; 33 | } 34 | bool create(int buf_len, const char * data) 35 | { 36 | release(); 37 | 38 | this->buf_len = buf_len; 39 | 40 | if( this->buf_len != 0) 41 | { 42 | this->characters = new char[this->buf_len]{}; 43 | } 44 | if(data) 45 | strncpy(this->characters, data, this->buf_len); 46 | 47 | return true; 48 | } 49 | bool release() 50 | { 51 | this->buf_len = 0; 52 | if(this->characters!=NULL) 53 | { 54 | delete []this->characters; 55 | this->characters = NULL; 56 | } 57 | return 0; 58 | } 59 | friend std::ostream & operator<<(std::ostream & os, const MyString & ms) 60 | { 61 | os << "buf_len = " << ms.buf_len; 62 | os << ", characters = " << static_cast(ms.characters); 63 | os << " [" << ms.characters << "]"; 64 | return os; 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /week11/examples/lab/matrix.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | -------------------------------------------------------------------------------- /week11/examples/lab/matrixdemo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Matrix 5 | { 6 | private: 7 | size_t rows; 8 | size_t cols; 9 | std::shared_ptr data; 10 | public: 11 | Matrix(size_t r, size_t c) 12 | { 13 | if ( r * c == 0) 14 | { 15 | rows = 0; 16 | cols = 0; 17 | data = nullptr; 18 | } 19 | else{ 20 | rows = r; 21 | cols = c; 22 | data = std::shared_ptr(new float[r * c]); 23 | } 24 | } 25 | Matrix(const Matrix & m): rows(m.rows), cols(m.cols), data(m.data){} 26 | 27 | friend std::ostream & operator<<(std::ostream & os, const Matrix & m) 28 | { 29 | os << "size (" << m.rows << "x" << m.cols << ")" << std::endl; 30 | os << "[" << std::endl; 31 | for (size_t r = 0; r < m.rows; r++) 32 | { 33 | for(size_t c = 0; c < m.cols; c++) 34 | os << m.data[r * m.rows + c] << ", "; 35 | os << std::endl; 36 | } 37 | os << "]"; 38 | return os; 39 | } 40 | }; 41 | 42 | int main() 43 | { 44 | Matrix m1(3,8); 45 | Matrix m2(4,8); 46 | 47 | m2 = m1; 48 | m1.setElement(1,2, 4.5f); 49 | std::cout << m2.getElement(1,2) << std::endl; 50 | 51 | std::cout << m1 << std::endl; 52 | std::cout << m2 << std::endl; 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /week11/examples/shared_ptr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class MyTime 5 | { 6 | int hours; 7 | int minutes; 8 | public: 9 | MyTime(): hours(0), minutes(0) 10 | { 11 | std::cout << "Constructor MyTime()" << std::endl; 12 | } 13 | MyTime(int m): hours(0), minutes(m) 14 | { 15 | std::cout << "Constructor MyTime(int)" << std::endl; 16 | this->hours += this->minutes / 60; 17 | this->minutes %= 60; 18 | } 19 | MyTime(int h, int m): hours(h), minutes(m) 20 | { 21 | std::cout << "Constructor MyTime(int,int)" << std::endl; 22 | this->hours += this->minutes / 60; 23 | this->minutes %= 60; 24 | } 25 | ~MyTime() 26 | { 27 | std::cout << "Destructor MyTime(). Bye!" << std::endl; 28 | } 29 | MyTime operator+(int m) const 30 | { 31 | MyTime sum; 32 | sum.minutes = this->minutes + m; 33 | sum.hours = this->hours; 34 | sum.hours += sum.minutes / 60; 35 | sum.minutes %= 60; 36 | return sum; 37 | } 38 | friend std::ostream & operator<<(std::ostream & os, const MyTime & t) 39 | { 40 | std::string str = std::to_string(t.hours) + " hours and " 41 | + std::to_string(t.minutes) + " minutes."; 42 | os << str; 43 | return os; 44 | } 45 | }; 46 | 47 | 48 | int main() 49 | { 50 | // std::shared_ptr mt0 = new MyTime(0,70); //error 51 | // MyTime * mt1 = std::make_shared(0, 70); //error 52 | // { 53 | // std::shared_ptr mt1(new MyTime(10)); 54 | // std::cout << *mt1 << std::endl; 55 | // } 56 | 57 | { 58 | std::shared_ptr mt0(new MyTime(70)); 59 | std::shared_ptr mt1 = std::make_shared(70); 60 | std::shared_ptr mt2 = mt1; 61 | std::shared_ptr mt3(mt2); 62 | 63 | std::cout << "mt1: " << *mt1 << std::endl; 64 | std::cout << "mt2: " << *mt2 << std::endl; 65 | std::cout << "mt3: " << *mt3 << std::endl; 66 | std::cout << "use_count() = " << mt2.use_count() << std::endl; 67 | 68 | { 69 | auto mt4 = mt3; 70 | *mt4 = *mt4 + 50; 71 | std::cout << "use_count() = " << mt3.use_count() << std::endl; 72 | } 73 | std::cout << "mt3: " << *mt3 << std::endl; 74 | std::cout << "use_count() = " << mt3.use_count() << std::endl; 75 | } 76 | 77 | std::shared_ptr numbers(new int[128]); //since C++17 78 | numbers[10] = 88; 79 | std::cout << numbers[10] << std::endl; 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /week11/examples/unique_ptr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class MyTime 5 | { 6 | int hours; 7 | int minutes; 8 | public: 9 | MyTime(): hours(0), minutes(0) 10 | { 11 | std::cout << "Constructor MyTime()" << std::endl; 12 | } 13 | MyTime(int m): hours(0), minutes(m) 14 | { 15 | std::cout << "Constructor MyTime(int)" << std::endl; 16 | this->hours += this->minutes / 60; 17 | this->minutes %= 60; 18 | } 19 | MyTime(int h, int m): hours(h), minutes(m) 20 | { 21 | std::cout << "Constructor MyTime(int,int)" << std::endl; 22 | this->hours += this->minutes / 60; 23 | this->minutes %= 60; 24 | } 25 | ~MyTime() 26 | { 27 | std::cout << "Destructor MyTime(). Bye!" << std::endl; 28 | } 29 | MyTime operator+(int m) const 30 | { 31 | MyTime sum; 32 | sum.minutes = this->minutes + m; 33 | sum.hours = this->hours; 34 | sum.hours += sum.minutes / 60; 35 | sum.minutes %= 60; 36 | return sum; 37 | } 38 | friend std::ostream & operator<<(std::ostream & os, const MyTime & t) 39 | { 40 | std::string str = std::to_string(t.hours) + " hours and " 41 | + std::to_string(t.minutes) + " minutes."; 42 | os << str; 43 | return os; 44 | } 45 | }; 46 | 47 | 48 | int main() 49 | { 50 | std::unique_ptr mt1(new MyTime(10)); 51 | std::unique_ptr mt2 = std::make_unique(80); //c++17 52 | 53 | std::cout << "mt1: " <<*mt1 << std::endl; 54 | std::cout << "mt2: " <<*mt2 << std::endl; 55 | 56 | // std::unique_ptr mt3 = mt1; // error 57 | std::unique_ptr mt3 = std::move(mt1); 58 | // std::shared_ptr mt3 = std::move(mt1);//okay 59 | 60 | // std::cout << "mt1: " <<*mt1 << std::endl; 61 | std::cout << "mt3: " <<*mt3 << std::endl; 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /week12/Lab12.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week12/Lab12.pdf -------------------------------------------------------------------------------- /week12/Lab12.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week12/Lab12.pptx -------------------------------------------------------------------------------- /week12/Lecture12.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week12/Lecture12.pdf -------------------------------------------------------------------------------- /week12/Lecture12.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week12/Lecture12.pptx -------------------------------------------------------------------------------- /week12/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 12: Class Inheritance 2 | 3 | ## Deriving a Class 4 | 5 | * Constructor 6 | * Destructor 7 | 8 | ## Access Control (protected) 9 | 10 | ## Static and Dynamic Binding 11 | 12 | ## Virtual Functions 13 | 14 | 15 | ## Dynamic Memory Management 16 | 17 | ## Lab 18 | -------------------------------------------------------------------------------- /week12/examples/derive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Base 5 | { 6 | public: 7 | int a; 8 | int b; 9 | Base(int a = 0, int b = 0) 10 | { 11 | this->a = a; 12 | this->b = b; 13 | cout << "Constructor Base::Base(" << a << ", " << b << ")" << endl; 14 | } 15 | ~Base() 16 | { 17 | cout << "Destructor Base::~Base()" << endl; 18 | } 19 | int product() 20 | { 21 | return a * b; 22 | } 23 | friend std::ostream & operator<<(std::ostream & os, const Base & obj) 24 | { 25 | os << "Base: a = " << obj.a << ", b = " << obj.b; 26 | return os; 27 | } 28 | }; 29 | 30 | class Derived: public Base 31 | { 32 | public: 33 | int c; 34 | Derived(int c): Base(c - 2, c - 1), c(c) 35 | { 36 | this->a += 3; //it can be changed after initialization 37 | cout << "Constructor Derived::Derived(" << c << ")" << endl; 38 | } 39 | ~Derived() 40 | { 41 | cout << "Destructor Derived::~Derived()" << endl; 42 | } 43 | int product() 44 | { 45 | return Base::product() * c; 46 | } 47 | friend std::ostream & operator<<(std::ostream & os, const Derived & obj) 48 | { 49 | // call the friend function in Base class 50 | os << static_cast(obj) << endl; 51 | 52 | os << "Derived: c = " << obj.c; 53 | return os; 54 | } 55 | }; 56 | 57 | int main() 58 | { 59 | { 60 | Base base(1, 2); 61 | cout << "Product = " << base.product() << endl; 62 | cout << base << endl; 63 | } 64 | cout << "----------------------" << endl; 65 | { 66 | Derived derived(5); 67 | cout << derived << endl; 68 | cout << "Product = " << derived.product() << endl; 69 | } 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /week12/examples/derived-memory/mystring.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class MyString 6 | { 7 | private: 8 | int buf_len; 9 | char * characters; 10 | public: 11 | MyString(int buf_len = 64, const char * data = NULL) 12 | { 13 | std::cout << "Constructor(int, char*)" << std::endl; 14 | this->buf_len = 0; 15 | this->characters = NULL; 16 | create(buf_len, data); 17 | } 18 | MyString(const MyString & ms) 19 | { 20 | std::cout << "Constructor(MyString&)" << std::endl; 21 | this->buf_len = 0; 22 | this->characters = NULL; 23 | create(ms.buf_len, ms.characters); 24 | } 25 | ~MyString() 26 | { 27 | release(); 28 | } 29 | MyString & operator=(const MyString &ms) 30 | { 31 | create(ms.buf_len, ms.characters); 32 | return *this; 33 | } 34 | bool create(int buf_len, const char * data) 35 | { 36 | release(); 37 | 38 | this->buf_len = buf_len; 39 | 40 | if( this->buf_len != 0) 41 | { 42 | this->characters = new char[this->buf_len]{}; 43 | } 44 | if(data) 45 | strncpy(this->characters, data, this->buf_len); 46 | 47 | return true; 48 | } 49 | bool release() 50 | { 51 | this->buf_len = 0; 52 | if(this->characters!=NULL) 53 | { 54 | delete []this->characters; 55 | this->characters = NULL; 56 | } 57 | return 0; 58 | } 59 | friend std::ostream & operator<<(std::ostream & os, const MyString & ms) 60 | { 61 | os << "buf_len = " << ms.buf_len; 62 | os << ", characters = " << static_cast(ms.characters); 63 | os << " [" << ms.characters << "]"; 64 | return os; 65 | } 66 | }; 67 | 68 | class MyMap: pubic MyString 69 | { 70 | private: 71 | char * keyname; 72 | MyMap(const char * key, const char * value) 73 | { 74 | ... 75 | } 76 | MyMap(const MyMap & mm): MyString(mm.buf_len, mm.characters) 77 | { 78 | //allocate memory for keyname 79 | //and hard copy from mm to *this 80 | } 81 | MyMap & operator=(const MyMap &mm) 82 | { 83 | MyMap::operator=(mm); 84 | //allocate memory for keyname 85 | //and hard copy from mm to *this 86 | return *this; 87 | } 88 | 89 | }; 90 | 91 | -------------------------------------------------------------------------------- /week12/examples/lab12/demo0.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Parent{ 5 | private: 6 | int id; 7 | string name; 8 | 9 | public: 10 | Parent():id(1),name("null"){ 11 | cout<<"calling default constructor Parent()\n"; 12 | } 13 | Parent(int i, string n):id(i),name(n){ 14 | cout<<"calling default constructor Parent(int,string)\n"; 15 | } 16 | 17 | friend ostream& operator<<(ostream&os, const Parent& p){ 18 | return os<<"Parent:"< 2 | #include 3 | using namespace std; 4 | class Parent{ 5 | private: 6 | int id; 7 | string name; 8 | 9 | public: 10 | Parent():id(1),name("null"){ 11 | cout<<"calling default constructor Parent()\n"; 12 | } 13 | Parent(int i, string n):id(i),name(n){ 14 | cout<<"calling default constructor Parent(int,string)\n"; 15 | } 16 | 17 | friend ostream& operator<<(ostream&os, const Parent& p){ 18 | return os<<"Parent:"< 2 | #include 3 | using namespace std; 4 | class Parent{ 5 | private: 6 | int id; 7 | string name; 8 | 9 | public: 10 | Parent():id(1),name("null"){ 11 | cout<<"calling default constructor Parent()\n"; 12 | } 13 | Parent(int i, string n):id(i),name(n){ 14 | cout<<"calling default constructor Parent(int,string)\n"; 15 | } 16 | 17 | friend ostream& operator<<(ostream&os, const Parent& p){ 18 | return os<<"Parent:"< 2 | #include 3 | using namespace std; 4 | class Parent{ 5 | private: 6 | int id; 7 | string name; 8 | 9 | public: 10 | Parent():id(1),name("null"){ 11 | cout<<"calling default constructor Parent()\n"; 12 | } 13 | Parent(int i, string n):id(i),name(n){ 14 | cout<<"calling default constructor Parent(int,string)\n"; 15 | } 16 | 17 | friend ostream& operator<<(ostream&os, const Parent& p){ 18 | return os<<"Parent:"< 2 | #include 3 | using namespace std; 4 | 5 | class Employee{ 6 | private: 7 | string name; 8 | string ssn; 9 | 10 | public: 11 | Employee(const string& n, const string& s): name(n),ssn(s){ 12 | cout<<"The base class constructor is invoked."<show(); 59 | 60 | pe=&se; 61 | pe->show(); 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /week12/examples/lab12/employee_destructor1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Employee{ 6 | private: 7 | string name; 8 | string ssn; 9 | 10 | public: 11 | Employee(const string& n, const string& s): name(n),ssn(s){ 12 | cout<<"The base class constructor is invoked."<show(); 57 | 58 | delete pe; 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /week12/examples/lab12/employee_destructor2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Employee{ 6 | private: 7 | string name; 8 | string ssn; 9 | 10 | public: 11 | Employee(const string& n, const string& s): name(n),ssn(s){ 12 | cout<<"The base class constructor is invoked."<show(); 57 | 58 | delete pe; 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /week12/examples/lab12/p_c_demo3.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | class Parent: 4 | def __init__(self, i=0, n="null"): 5 | print("calling Parent default constructor Parent()") 6 | self.id = i 7 | self.name = n # Python 字符串不可变,无需手动内存管理 8 | 9 | def __deepcopy__(self, memo): 10 | print("calling Parent copy constructor Parent(const Parent&)") 11 | new_obj = self.__class__(self.id, self.name) 12 | memo[id(self)] = new_obj 13 | return new_obj 14 | 15 | def assign(self, other): 16 | print("call Parent assignment operator:") 17 | if self is other: 18 | return self 19 | self.id = other.id 20 | self.name = other.name 21 | return self 22 | 23 | def __del__(self): 24 | print("call Parent destructor.") # 实际无需手动释放资源 25 | 26 | def __str__(self): 27 | return f"Parent:{self.id}, {self.name}\n" 28 | 29 | class Child(Parent): 30 | def __init__(self, i=0, n="null", s="null", a=0): 31 | super().__init__(i, n) 32 | print("call Child default constructor Child()") 33 | self.style = s 34 | self.age = a 35 | 36 | def __deepcopy__(self, memo): 37 | print("calling Child copy constructor Child(const Child&)") 38 | new_obj = self.__class__(self.id, self.name, self.style, self.age) 39 | memo[id(self)] = new_obj 40 | return new_obj 41 | 42 | def assign(self, other): 43 | print("call Child assignment operator:") 44 | if self is other: 45 | return self 46 | super().assign(other) 47 | self.style = other.style 48 | self.age = other.age 49 | return self 50 | 51 | def __del__(self): 52 | super().__del__() 53 | print("call Child destructor.") # 父类 __del__ 会自动调用 54 | 55 | def __str__(self): 56 | #parent_str = super().__str__().replace("Parent:", "Child:", 1) 57 | parent_str = super().__str__() 58 | return f"{parent_str}Child:{self.style}, {self.age}\n" 59 | 60 | if __name__ == "__main__": 61 | # 模拟 C++ 对象构造 62 | p1 = Parent() 63 | print("value in p1\n", p1) 64 | 65 | p2 = Parent(101, "Liming") 66 | print("value in p2\n", p2) 67 | 68 | p3 = copy.deepcopy(p1) 69 | print("value in p3\n", p3) 70 | 71 | p1.assign(p2) 72 | print("value in p1\n", p1) 73 | 74 | # 子类测试 75 | c1 = Child() 76 | print("value in c1\n", c1) 77 | 78 | c2 = Child(201, "Wuhong", "teenager", 15) 79 | print("value in c2\n", c2) 80 | 81 | c3 = copy.deepcopy(c1) 82 | print("value in c3\n", c3) 83 | 84 | c1.assign(c2) 85 | print("value in c1\n", c1) 86 | 87 | # 手动触发析构(Python 垃圾回收时机不确定) 88 | del c3, c2, c1, p3, p2, p1 89 | 90 | -------------------------------------------------------------------------------- /week12/examples/matrix/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "matrix.h" 3 | 4 | int main() 5 | { 6 | Matrix * matA = createMat(2, 3); 7 | Matrix * matB = createMat(2, 3); 8 | Matrix * matC = createMat(2, 3); 9 | Matrix * matD = createMat(3, 2); 10 | Matrix * matNULL = NULL; 11 | 12 | //initialization 13 | //You should have your own method to do it 14 | matA->data[3] = 2.3f; 15 | matB->data[3] = 3.1f; 16 | 17 | if(! add(matA, matB, matC)) 18 | fprintf(stderr, "Matrix addition failed."); 19 | else 20 | { 21 | //You can have a better method to show the results 22 | printf("result=%f\n", matC->data[3]); 23 | } 24 | 25 | //more tests 26 | add(matA, matB, matD); 27 | 28 | add(matNULL, matB, matC); 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /week12/examples/matrix/matrix.h: -------------------------------------------------------------------------------- 1 | #ifndef _MATRIX_H 2 | #define _MATRIX_H 3 | 4 | #include //for bool 5 | 6 | typedef struct Matrix_{ //use typedef to simplify type name 7 | size_t rows; // use size_t, not int 8 | size_t cols; // use size_t, not int 9 | float * data; 10 | } Matrix; 11 | 12 | Matrix * createMat(size_t rows, size_t cols); 13 | bool releaseMat(Matrix * p); 14 | bool add(const Matrix * input1, const Matrix * input2, Matrix *output); 15 | 16 | #endif -------------------------------------------------------------------------------- /week12/examples/protect.cpp: -------------------------------------------------------------------------------- 1 | class Base 2 | { 3 | protected: 4 | int n; 5 | private: 6 | void foo1(Base& b) 7 | { 8 | n++; // Okay 9 | b.n++; // Okay 10 | } 11 | }; 12 | 13 | class Derived : public Base 14 | { 15 | void foo2(Base& b, Derived& d) 16 | { 17 | n++; //Okay 18 | this->n++; //Okay 19 | //b.n++; //Error. You cannot access a protected member through base 20 | d.n++; //Okay 21 | } 22 | }; 23 | 24 | void compare(Base& b, Derived& d) // a non-member non-friend function 25 | { 26 | // b.n++; // Error 27 | // d.n++; // Error 28 | } -------------------------------------------------------------------------------- /week12/examples/virtual.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Person 6 | { 7 | public: 8 | string name; 9 | Person(string n): name(n){} 10 | void print() 11 | { 12 | cout << "Name: " << name << endl; 13 | } 14 | }; 15 | 16 | class Person2 17 | { 18 | public: 19 | string name; 20 | Person2(string n): name(n){} 21 | virtual void print() = 0; 22 | }; 23 | 24 | class Student: public Person 25 | { 26 | public: 27 | string id; 28 | Student(string n, string i): Person(n), id(i){} 29 | void print() 30 | { 31 | cout << "Name: " << name; 32 | cout << ". ID: " << id << endl; 33 | } 34 | }; 35 | 36 | void printObjectInfo(Person & p) 37 | { 38 | p.print(); 39 | } 40 | 41 | int main() 42 | { 43 | { 44 | Student stu("yu", "2019"); 45 | printObjectInfo(stu); 46 | } 47 | 48 | { 49 | Person * p = new Student("xue", "2020"); 50 | p->print(); //if print() is not a virtual function, different output 51 | delete p; //if its destructor is not virtual 52 | } 53 | 54 | // { //if you want to call a function in the base class 55 | // Student stu("li", "2021"); 56 | // stu.Person::print(); 57 | 58 | // Person * p = new Student("xue", "2020"); 59 | // p->Person::print(); 60 | // delete p; 61 | // } 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /week13/Lab13.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week13/Lab13.pdf -------------------------------------------------------------------------------- /week13/Lab13.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week13/Lab13.pptx -------------------------------------------------------------------------------- /week13/Lecture13.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week13/Lecture13.pdf -------------------------------------------------------------------------------- /week13/Lecture13.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week13/Lecture13.pptx -------------------------------------------------------------------------------- /week13/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 13: Class Templates and std Library 2 | 3 | ## Class Templates 4 | 5 | ## Template Non-Type Parameters 6 | 7 | ## Class Template Specialization 8 | 9 | ## Templates in std 10 | 11 | ### Lab 12 | 13 | Create a matrix template class which can handle different data types. 14 | -------------------------------------------------------------------------------- /week13/examples/matclass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Class IntMat 5 | class IntMat 6 | { 7 | size_t rows; 8 | size_t cols; 9 | int * data; 10 | public: 11 | IntMat(size_t rows, size_t cols): 12 | rows(rows), cols(cols) 13 | { 14 | data = new int[rows * cols]{}; 15 | } 16 | ~IntMat() 17 | { 18 | delete [] data; 19 | } 20 | IntMat(const IntMat&) = delete; 21 | IntMat& operator=(const IntMat&) = delete; 22 | int getElement(size_t r, size_t c); 23 | bool setElement(size_t r, size_t c, int value); 24 | }; 25 | int IntMat::getElement(size_t r, size_t c) 26 | { 27 | if ( r >= this->rows || c >= this->cols) 28 | { 29 | cerr << "Indices are out of range" << endl; 30 | return 0; 31 | } 32 | return data[ this->cols * r + c]; 33 | } 34 | bool IntMat::setElement(size_t r, size_t c, int value) 35 | { 36 | if ( r >= this->rows || c >= this->cols) 37 | return false; 38 | 39 | data[ this->cols * r + c] = value; 40 | return true; 41 | } 42 | 43 | // Class FloatMat 44 | class FloatMat 45 | { 46 | size_t rows; 47 | size_t cols; 48 | float * data; 49 | public: 50 | FloatMat(size_t rows, size_t cols): 51 | rows(rows), cols(cols) 52 | { 53 | data = new float[rows * cols]{}; 54 | } 55 | ~FloatMat() 56 | { 57 | delete [] data; 58 | } 59 | FloatMat(const FloatMat&) = delete; 60 | FloatMat& operator=(const FloatMat&) = delete; 61 | float getElement(size_t r, size_t c); 62 | bool setElement(size_t r, size_t c, float value); 63 | }; 64 | float FloatMat::getElement(size_t r, size_t c) 65 | { 66 | if ( r >= this->rows || c >= this->cols) 67 | { 68 | cerr << "getElement(): Indices are out of range" << endl; 69 | return 0.f; 70 | } 71 | return data[ this->cols * r + c]; 72 | } 73 | bool FloatMat::setElement(size_t r, size_t c, float value) 74 | { 75 | if ( r >= this->rows || c >= this->cols) 76 | { 77 | cerr << "setElement(): Indices are out of range" << endl; 78 | return false; 79 | } 80 | data[ this->cols * r + c] = value; 81 | return true; 82 | } 83 | 84 | int main() 85 | { 86 | IntMat imat(3,4); 87 | imat.setElement(1, 2, 256); 88 | FloatMat fmat(2,3); 89 | fmat.setElement(1, 2, 3.14159f); 90 | 91 | // FloatMat fmat2(fmat); //error 92 | 93 | // FloatMat fmat3(2,3); 94 | // fmat3 = fmat; //error 95 | 96 | cout << imat.getElement(1,2) << endl; 97 | cout << fmat.getElement(1,2) << endl; 98 | 99 | return 0; 100 | } -------------------------------------------------------------------------------- /week13/examples/mattemplate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Class Template 5 | template 6 | class Mat 7 | { 8 | size_t rows; 9 | size_t cols; 10 | T * data; 11 | public: 12 | Mat(size_t rows, size_t cols): rows(rows), cols(cols) 13 | { 14 | data = new T[rows * cols]{}; 15 | } 16 | ~Mat() 17 | { 18 | delete [] data; 19 | } 20 | Mat(const Mat&) = delete; 21 | Mat& operator=(const Mat&) = delete; 22 | T getElement(size_t r, size_t c); 23 | bool setElement(size_t r, size_t c, T value); 24 | }; 25 | template 26 | T Mat::getElement(size_t r, size_t c) 27 | { 28 | if ( r >= this->rows || c >= this->cols) 29 | { 30 | cerr << "getElement(): Indices are out of range" << endl; 31 | return 0; 32 | } 33 | return data[ this->cols * r + c]; 34 | } 35 | template 36 | bool Mat::setElement(size_t r, size_t c, T value) 37 | { 38 | if ( r >= this->rows || c >= this->cols) 39 | { 40 | cerr << "setElement(): Indices are out of range" << endl; 41 | return false; 42 | } 43 | 44 | data[ this->cols * r + c] = value; 45 | return true; 46 | } 47 | 48 | template class Mat; // Explicitly instantiate template Mat 49 | //template Mat and Mat will be instantiate implicitly 50 | int main() 51 | { 52 | Mat imat(3,4); 53 | imat.setElement(1, 2, 256); 54 | Mat fmat(2,3); 55 | fmat.setElement(1, 2, 3.14159f); 56 | Mat dmat(2,3); 57 | dmat.setElement(1, 2, 2.718281828); 58 | 59 | // Mat fmat2(fmat); //error 60 | 61 | // Mat fmat3(2,3); 62 | // fmat3 = fmat; //error 63 | 64 | cout << imat.getElement(1,2) << endl; 65 | cout << fmat.getElement(1,2) << endl; 66 | cout << dmat.getElement(1,2) << endl; 67 | 68 | return 0; 69 | } -------------------------------------------------------------------------------- /week13/examples/nontypeparam.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Class Template 5 | template 6 | class Mat 7 | { 8 | T data[rows][cols]; 9 | public: 10 | Mat(){} 11 | //// the default copy constructor will copy each element of a static array member 12 | //// so we do not 'delete' the copy constructor 13 | //// the same with the assignment operator 14 | // Mat(const Mat&) = delete; 15 | // Mat& operator=(const Mat&) = delete; 16 | T getElement(size_t r, size_t c); 17 | bool setElement(size_t r, size_t c, T value); 18 | }; 19 | template 20 | T Mat::getElement(size_t r, size_t c) 21 | { 22 | if ( r >= rows || c >= cols) 23 | { 24 | cerr << "getElement(): indices are out of range" << endl; 25 | return 0; 26 | } 27 | return data[r][c]; 28 | } 29 | template 30 | bool Mat::setElement(size_t r, size_t c, T value) 31 | { 32 | if ( r >= rows || c >= cols) 33 | { 34 | cerr << "setElement(): Indices are out of range" << endl; 35 | return false; 36 | } 37 | 38 | data[r][c] = value; 39 | return true; 40 | } 41 | 42 | template class Mat; // Explicitly instantiate template Mat 43 | typedef Mat Mat22i; 44 | 45 | //template Mat will be instantiate implicitly 46 | 47 | int main() 48 | { 49 | Mat22i mat; 50 | 51 | mat.setElement(2, 3, 256); 52 | cout << mat.getElement(2, 3) << endl; 53 | 54 | mat.setElement(1, 1, 256); 55 | cout << mat.getElement(1, 1) << endl; 56 | 57 | Mat vec; 58 | vec.setElement(2, 0, 3.14159f); 59 | cout << vec.getElement(2, 0) << endl; 60 | 61 | Mat vec2(vec); 62 | cout << vec2.getElement(2, 0) << endl; 63 | 64 | // vec2 = mat; //error 65 | 66 | return 0; 67 | } -------------------------------------------------------------------------------- /week14/Lab14.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week14/Lab14.pdf -------------------------------------------------------------------------------- /week14/Lab14.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week14/Lab14.pptx -------------------------------------------------------------------------------- /week14/Lecture14.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week14/Lecture14.pdf -------------------------------------------------------------------------------- /week14/Lecture14.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week14/Lecture14.pptx -------------------------------------------------------------------------------- /week14/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 14: Error Handling 2 | 3 | ## Standard Output Stream and Standard Error Stream 4 | 5 | ## assert 6 | 7 | ## Exceptions 8 | 9 | ## More About Exceptions -------------------------------------------------------------------------------- /week14/examples/assert.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char ** argv) 5 | { 6 | assert( argc == 2); 7 | std::cout << "This is an assert example." << std::endl; 8 | return 0; 9 | } 10 | -------------------------------------------------------------------------------- /week14/examples/derived.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Base 4 | { 5 | public: 6 | Base() {} 7 | }; 8 | 9 | class Derived: public Base 10 | { 11 | public: 12 | Derived() {} 13 | }; 14 | 15 | int main() 16 | { 17 | try 18 | { 19 | throw Derived(); 20 | } 21 | catch (const Base& base) 22 | { 23 | std::cerr << "I caught Base." << std::endl; 24 | } 25 | catch (const Derived& derived) 26 | { // never reach here 27 | std::cerr << "I caught Derived." << std::endl; 28 | } 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /week14/examples/error1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | float ratio(float a, float b) 6 | { 7 | if (fabs(a + b) < FLT_EPSILON) 8 | { 9 | std::cerr << "The sum of the two arguments is close to zero." << std::endl; 10 | std::abort(); 11 | } 12 | return (a - b) / (a + b); 13 | //return int(a - b) / int(a + b);// divided by zero behavior differently for int and float 14 | } 15 | 16 | int main() 17 | { 18 | float x = 0.f; 19 | float y = 0.f; 20 | float z = 0.f; 21 | 22 | std::cout << "Please input two numbers :"; 23 | while (std::cin >> x >> y) 24 | { 25 | z = ratio(x,y); 26 | std::cout << "ratio(" << x << ", " << y<< ") = " << z << std::endl; 27 | std::cout << "Please input two numbers :"; 28 | } 29 | std::cout << "Bye!" << std::endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /week14/examples/error2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | bool ratio(float a, float b, float & c) 6 | { 7 | if (fabs(a + b) < FLT_EPSILON) 8 | { 9 | std::cerr << "The sum of the two arguments is close to zero." << std::endl; 10 | return false; 11 | } 12 | c = (a - b) / (a + b); 13 | return true; 14 | } 15 | 16 | int main() 17 | { 18 | float x = 0.f; 19 | float y = 0.f; 20 | float z = 0.f; 21 | 22 | std::cout << "Please input two numbers :"; 23 | while (std::cin >> x >> y) 24 | { 25 | bool ret = ratio(x, y, z); 26 | if(ret) 27 | std::cout << "ratio(" << x << ", " << y<< ") = " << z << std::endl; 28 | else 29 | std::cerr << "ratio(" << x << ", " << y<< ") failed." << std::endl; 30 | 31 | std::cout << "Please input two numbers :"; 32 | } 33 | std::cout << "Bye!" << std::endl; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /week14/examples/error3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | float ratio(float a, float b) 7 | { 8 | if (fabs(a + b) < FLT_EPSILON) 9 | throw "The sum of the two arguments is close to zero."; 10 | 11 | return (a - b) / (a + b); 12 | } 13 | 14 | int main() 15 | { 16 | float x = 0.f; 17 | float y = 0.f; 18 | float z = 0.f; 19 | 20 | std::cout << "Please input two numbers :"; 21 | while (std::cin >> x >> y) 22 | { 23 | { //try and catch 24 | try{ 25 | z = ratio(x,y); 26 | std::cout << "ratio(" << x << ", " << y<< ") = " << z << std::endl; 27 | } 28 | catch(const char * msg) 29 | { 30 | std::cerr << "Call ratio() failed: " << msg << std::endl; 31 | std::cerr << "I give you another chance." << std::endl; 32 | } 33 | } 34 | 35 | // { //if no try-catch 36 | // z = ratio(x,y); 37 | // std::cout << "ratio(" << x << ", " << y<< ") = " << z << std::endl; 38 | // } 39 | 40 | std::cout << "Please input two numbers :"; 41 | } 42 | std::cout << "Bye!" << std::endl; 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /week14/examples/error4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | float ratio(float a, float b) 7 | { 8 | if (a < 0) 9 | throw 1; 10 | if (b < 0) 11 | throw 2; 12 | if (fabs(a + b) < FLT_EPSILON) 13 | throw "The sum of the two arguments is close to zero."; 14 | 15 | return (a - b) / (a + b); 16 | } 17 | 18 | int main() 19 | { 20 | float x = 0.f; 21 | float y = 0.f; 22 | float z = 0.f; 23 | 24 | std::cout << "Please input two numbers :"; 25 | while (std::cin >> x >> y) 26 | { 27 | try{ 28 | z = ratio(x,y); 29 | std::cout << "ratio(" << x << ", " << y<< ") = " << z << std::endl; 30 | } 31 | catch(const char * msg) 32 | { 33 | std::cerr << "Call ratio() failed: " << msg << std::endl; 34 | std::cerr << "I give you another chance." << std::endl; 35 | } 36 | catch(int eid) 37 | { 38 | if (eid == 1) 39 | std::cerr << "Call ratio() failed: the 1st argument should be positive." << std::endl; 40 | else if (eid == 2) 41 | std::cerr << "Call ratio() failed: the 2nd argument should be positive." << std::endl; 42 | else 43 | std::cerr << "Call ratio() failed: unrecognized error code." << std::endl; 44 | 45 | std::cerr << "I give you another chance." << std::endl; 46 | } 47 | 48 | std::cout << "Please input two numbers :"; 49 | } 50 | std::cout << "Bye!" << std::endl; 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /week14/examples/error5.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | float ratio(float a, float b) 6 | { 7 | if (a < 0) 8 | throw 1; 9 | if (b < 0) 10 | throw 2; 11 | if (fabs(a + b) < FLT_EPSILON) 12 | throw "The sum of the two arguments is close to zero."; 13 | 14 | return (a - b) / (a + b); 15 | } 16 | 17 | float ratio_wrapper(float a, float b) 18 | { 19 | try{ 20 | return ratio(a, b); 21 | } 22 | catch(int eid) 23 | { 24 | if (eid == 1) 25 | std::cerr << "Call ratio() failed: the 1st argument should be positive." << std::endl; 26 | else if (eid == 2) 27 | std::cerr << "Call ratio() failed: the 2nd argument should be positive." << std::endl; 28 | else 29 | std::cerr << "Call ratio() failed: unrecognized error code." << std::endl; 30 | } 31 | return 0; 32 | } 33 | 34 | int main() 35 | { 36 | float x = 0.f; 37 | float y = 0.f; 38 | float z = 0.f; 39 | 40 | std::cout << "Please input two numbers :"; 41 | while (std::cin >> x >> y) 42 | { 43 | try{ 44 | z = ratio_wrapper(x,y); 45 | std::cout << "ratio(" << x << ", " << y<< ") = " << z << std::endl; 46 | } 47 | catch(const char * msg) 48 | { 49 | std::cerr << "Call ratio() failed: " << msg << std::endl; 50 | std::cerr << "I give you another chance." << std::endl; 51 | } 52 | 53 | std::cout << "Please input two numbers :"; 54 | } 55 | std::cout << "Bye!" << std::endl; 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /week14/examples/nothrow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | size_t length = 80000000000L; 8 | int * p = NULL; 9 | 10 | try { 11 | cout << "Trying to allocate a big block of memory" << endl; 12 | p = new int[length]; 13 | //p = new(nothrow) int[length]; 14 | cout << "No exception." << endl; 15 | } 16 | catch (std::bad_alloc & ba) 17 | { 18 | cout << "bad_alloc exception!" << endl; 19 | cout << ba.what() << endl; 20 | } 21 | 22 | if(p) 23 | cout << "Memory successfully allocated." << endl; 24 | else 25 | cout << "So bad, null pointer." << endl; 26 | 27 | // for(size_t i = 0; i < length; i++) 28 | // p[i] = i; 29 | // size_t sum; 30 | // for(size_t i = 0; i < length; i++) 31 | // sum += p[i]; 32 | // cout << "Sum = " << sum << endl; 33 | if(p) 34 | delete [] p; 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /week14/examples/stderr.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void div2(int n) 4 | { 5 | if( n % 2 != 0) 6 | { 7 | fprintf(stderr, "Error: The input must be an even number. Here it's %d\n", n); 8 | } 9 | else 10 | { 11 | int result = n / 2; 12 | fprintf(stdout, "Info: The result is %d\n", result); 13 | } 14 | return; 15 | } 16 | 17 | int main() 18 | { 19 | for(int n = -5; n <= 5; n++) 20 | div2(n); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /week14/examples/stderr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void div2(int n) 4 | { 5 | if( n % 2 != 0) 6 | { 7 | std::cerr << "Error: The input must be an even number. Here it's " << n << "." << std::endl; 8 | } 9 | else 10 | { 11 | int result = n / 2; 12 | std::cout << "Info: The result is " << result << "." << std::endl; 13 | } 14 | return; 15 | } 16 | 17 | int main() 18 | { 19 | for(int n = -5; n <= 5; n++) 20 | div2(n); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /week15/Lab15.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week15/Lab15.pdf -------------------------------------------------------------------------------- /week15/Lab15.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week15/Lab15.pptx -------------------------------------------------------------------------------- /week15/Lecture15.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week15/Lecture15.pdf -------------------------------------------------------------------------------- /week15/Lecture15.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShiqiYu/CPP/a6005e35a263c037cafadd6874c51dd9cba95d3e/week15/Lecture15.pptx -------------------------------------------------------------------------------- /week15/README.md: -------------------------------------------------------------------------------- 1 | # Chapter 15: Nested Classes and RTTI 2 | 3 | ## Unit Test 4 | 5 | ## Nested Classes 6 | 7 | ## Runtime Type Identification and Type Cast Operators 8 | -------------------------------------------------------------------------------- /week15/examples/const_cast.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int value1 = 100; 7 | const int value2 = 200; 8 | cout << "value1 = " << value1 << endl; 9 | cout << "value2 = " << value2 << endl; 10 | 11 | // int * pv1 = &value1; 12 | int * pv1 = const_cast(&value1); 13 | // int * pv2 = &value2; // error 14 | int * pv2 = const_cast(&value2); 15 | 16 | (*pv1)++; 17 | (*pv2)++; 18 | 19 | cout << "value1 = " << (*pv1) << endl; 20 | cout << "value2 = " << (value2) << endl; 21 | 22 | // // int & v2 = value2; //error 23 | // int& v2 = const_cast(value2); 24 | // v2++; 25 | // cout << "value2 = " << value2 << endl; 26 | 27 | // cout << "*pv2 = " << (*pv2) << endl; 28 | // cout << "v2 = " << v2 << endl; 29 | 30 | return 0; 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /week15/examples/friend.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Sniper; 5 | 6 | class Supplier 7 | { 8 | int storage; 9 | public: 10 | Supplier(int storage = 1000): storage(storage){} 11 | 12 | // bool foo(Sniper & sniper){sniper.bullets++;} 13 | bool provide(Sniper & sniper); 14 | }; 15 | 16 | class Sniper 17 | { 18 | private: 19 | int bullets; 20 | public: 21 | Sniper(int bullets = 0): bullets(bullets){} 22 | // friend class Supplier; 23 | friend bool Supplier::provide(Sniper & sniper); 24 | }; 25 | 26 | bool Supplier::provide(Sniper & sniper) 27 | { 28 | // bullets is a private member 29 | if (sniper.bullets < 20) //no enough bullets 30 | { 31 | if (this->storage > 100 ) 32 | { 33 | sniper.bullets += 100; 34 | this->storage -= 100; 35 | } 36 | else if(this->storage > 0) 37 | { 38 | sniper.bullets += this->storage; 39 | this->storage = 0; 40 | } 41 | else 42 | return false; 43 | } 44 | cout << "sniper has " << sniper.bullets << " bullets now." << endl; 45 | return true; 46 | } 47 | 48 | int main() 49 | { 50 | Sniper sniper(2); 51 | Supplier supplier(2000); 52 | supplier.provide(sniper); 53 | return 0; 54 | } -------------------------------------------------------------------------------- /week15/examples/friend2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Supplier; 5 | class Sniper; 6 | 7 | class Supplier 8 | { 9 | int storage; 10 | public: 11 | Supplier(int storage = 1000): storage(storage){} 12 | bool provide(Sniper & sniper); 13 | }; 14 | 15 | class Sniper 16 | { 17 | private: 18 | int bullets; 19 | public: 20 | Sniper(int bullets = 0): bullets(bullets){} 21 | friend bool Supplier::provide(Sniper &); 22 | }; 23 | 24 | bool Supplier::provide(Sniper & sniper) 25 | { 26 | // bullets is a private member 27 | if (sniper.bullets < 20) //no enough bullets 28 | { 29 | if (this->storage > 100 ) 30 | { 31 | sniper.bullets += 100; 32 | this->storage -= 100; 33 | } 34 | else if(this->storage > 0) 35 | { 36 | sniper.bullets += this->storage; 37 | this->storage = 0; 38 | } 39 | else 40 | return false; 41 | } 42 | cout << "sniper has " << sniper.bullets << " bullets now." << endl; 43 | return true; 44 | } 45 | int main() 46 | { 47 | Sniper sniper(2); 48 | Supplier supplier(2000); 49 | supplier.provide(sniper); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /week15/examples/nested-enum1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | enum DataType 4 | { 5 | TYPE8U, 6 | TYPE8S, 7 | TYPE32F, 8 | TYPE64F 9 | }; 10 | class Mat 11 | { 12 | private: 13 | DataType type; 14 | void * data; 15 | public: 16 | Mat(DataType type) : type(type), data(NULL){} 17 | 18 | DataType getType() const { return type; } 19 | }; 20 | 21 | int main() 22 | { 23 | Mat image(TYPE8U); 24 | 25 | if (image.getType() == TYPE8U) 26 | std::cout << "This is an 8U matrix." << std::endl; 27 | else 28 | std::cout << "I am not an 8U matrix." << std::endl; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /week15/examples/nested-enum2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | class Mat 5 | { 6 | public: 7 | enum DataType 8 | { 9 | TYPE8U, 10 | TYPE8S, 11 | TYPE32F, 12 | TYPE64F 13 | }; 14 | private: 15 | DataType type; 16 | void * data; 17 | public: 18 | Mat(DataType type) : type(type), data(NULL){} 19 | 20 | DataType getType() const { return type; } 21 | }; 22 | 23 | int main() 24 | { 25 | Mat image(Mat::DataType::TYPE8U); 26 | 27 | if (image.getType() == Mat::DataType::TYPE8U) 28 | std::cout << "This is an 8U matrix." << std::endl; 29 | else 30 | std::cout << "I am not an 8U matrix." << std::endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /week15/examples/nestedclass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Storage 4 | { 5 | public: 6 | class Fruit 7 | { 8 | string name; 9 | int weight; 10 | public: 11 | Fruit(string name="", int weight=0):name(name), weight(weight){} 12 | string getInfo(){return name + ", weight " + to_string(weight) + "kg.";} 13 | }; 14 | private: 15 | Fruit fruit; 16 | public: 17 | Storage(Fruit f) 18 | { 19 | this->fruit = f; 20 | } 21 | void print() 22 | { 23 | cout << fruit.getInfo() << endl; 24 | } 25 | 26 | }; 27 | 28 | int main() 29 | { 30 | Storage::Fruit apple("apple", 100); 31 | Storage mystorage(apple); 32 | mystorage.print(); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /week15/examples/reinterpret_cast.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int i = 18; 7 | float * p1 = reinterpret_cast(i); // static_cast will fail 8 | int * p2 = reinterpret_cast(p1); 9 | 10 | printf("p1=%p\n", p1); 11 | printf("p2=%p\n", p2); 12 | 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /week15/examples/rtti.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Person 5 | { 6 | protected: 7 | string name; 8 | public: 9 | Person(string name=""):name(name){}; 10 | virtual ~Person(){} 11 | string getInfo(){return name;} 12 | }; 13 | 14 | class Student: public Person 15 | { 16 | string studentid; 17 | public: 18 | Student(string name="", string sid=""):Person(name),studentid(sid){}; 19 | string getInfo(){return name+":("+studentid + ")";} 20 | }; 21 | 22 | int main() 23 | { 24 | Person person("Yu"); 25 | Student student("Sam", "20210212"); 26 | Person* pp = &student; 27 | Person& rp = student; 28 | Student * ps = (Student*)&person; // danger! 29 | cout << "person.getInfo():" << person.getInfo() << endl; 30 | cout << "pp->getInfo():" << pp->getInfo() << endl; 31 | cout << "rp.getInfo():" <getInfo():" << ps->getInfo() << endl; // danger if getInfo is not virtual 33 | 34 | char * p = (char*) 100; 35 | // ps = dynamic_cast(&person); 36 | // printf("address = %p\n", ps); 37 | // pp = dynamic_cast(&student); 38 | // printf("address = %p\n", pp); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /week15/examples/typeid.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Person 7 | { 8 | protected: 9 | string name; 10 | public: 11 | Person(string name=""):name(name){}; 12 | virtual ~Person(){} 13 | string getInfo(){return name;} 14 | }; 15 | 16 | class Student: public Person 17 | { 18 | string studentid; 19 | public: 20 | Student(string name="", string sid=""):Person(name),studentid(sid){}; 21 | string getInfo(){return name+":"+studentid;} 22 | }; 23 | 24 | int main() 25 | { 26 | string s("hello"); 27 | 28 | cout << "typeid.name of s is " << typeid(s).name() << endl; 29 | cout << "typeid.name of std::string is " << typeid(std::string).name() << endl; 30 | cout << "typeid.name of Student is " << typeid(Student).name() << endl; 31 | 32 | if(typeid(std::string) == typeid(s)) 33 | cout << "s is a std::string object." << endl; 34 | 35 | return 0; 36 | } 37 | 38 | --------------------------------------------------------------------------------