CS106L
CS106L 2023 winter official website
About¶
为什么要学CS106L?24年国庆节之后入职的实习需要使用到C++和C#,想要趁着国庆假期将斯坦福的CS106B以及CS106L都学习一下。
lecture1 welcome¶
CS106L focus on code: what makes it good, what powerful and elegant code looks like.
Only STL.
understand how and why C++ was made.
C language: no objects or classes, difficult to write generic code
C++ was created by Bjarne Stroutstrup in 1983
Design philosophy of C++:
- only add features if they solve an actual problem
- programmers should be free to choose their own sytle
- compartmentalization is key
- Allow the programmer full control of if they want it
- don't sacrifice performance except as a last resort
- enforce safety at compile time whenever possible
lecture2 types and structs¶
using namespace std;
is not good style
STL - standard template library
Namespace for the STL is std
2.1 types¶
C++ fundamental types:
#include <string>
int val = 5; //32 bits
char ch = 'F'; //8 bits (usually)
float decimalVal1 = 5.0; //32 bits (usually)
double decimalVal2 = 5.0; //64 bits (usually)
bool bVal = true; //1 bit
std::string str = "sarah";
C++ is a statically typed language, everything with a name(variables, functions, etc) is given a type before runtime
dynamically typed: everything with a name is given a type at runtim based on the thing's current value
If the type is wrong, Python crash during runtime, but C++ compile error and the code will never run
2.2 overloading¶
overloading: defien two functions with the same name but different types.
int half(int x, int divisor = 2) {
return x / divisor;
}
double half(double x) {
return x / 2;
}
half(4) // uses version (1), returns 2
half(3, 3) // uses version (1), returns 1
half(3.0) // uses version (2), returns 1.5
2.3 structs¶
Two methods of initializing a struct.
#include <iostream>
struct Student {
std::string name;
std::string state;
int age;
};
void printStudentInfo(Student s) {
std::cout << s.name << std::endl;
std::cout << s.state << std::endl;
std::cout << s.age << std:: endl;
}
int main () {
Student s1;
s1.name = "Charles";
s1.state = "Zhejiang";
s1.age = 24;
printStudentInfo(s1);
Student s2 = {"Chi Le", "Suzhou", 22};
printStudentInfo(s2);
}
2.4 std::pair¶
std::pair
is an STL build-in struct with two fields of any type.
std::pair
is a template, you specify the types of the fields inside <> for each pair object you make
The fields in std::pair
s are named first and second
std::pair<bool, Student> lookupStudent(string name) {
Student blank;
if (notFound(name)) return std::make_pair(false, blank);
Student result = getStudentWithName(name);
return std::make_pair(true, result);
}
std::pair<bool, Student> output = lookupStudent(“Julie”);
2.5 type deduction with auto
类型自动推倒auto¶
the type of a variant is deduced by the compiler
Note:
auto d = "Hello"; // char* -> it is a C string