Cpp-types, structs, ini, ref, streams
very basic STL
1 |
|
std:::The STL
- Tons of general functionality
- Built in classes like maps, sets, vectors
- Accessed through the namespace std::
- Extremely powerful and well-maintained
using namespace std;is not a good style!
types
more fundemental types: std::string str = "Haven";
C++: a interpreted language (Types before program runs during compilation)
C++ allows function overloading!auto: a keyword that tell the compiler to deduce the type of a object or a varible
- only use when the types are obvious
- or when the type is annoyingly verbose to write out
structs
STL have its own structs!std::pair: struct with 2 fields of any type(first and second)
initialization
1 | int criticalSystemValue(42.5); |
what is wrong?
42.5 is not a int, but C++ not care.
C++ not check with ini value, so it might cause narrowing conversation.
uniform ini (C++11)
int numOne{12.0}; with these uniform ini, C++ does care about types!
features:
- safe: do not allow for narrowing conversions
- ubiquitous: works for all types!
structures ini
1 | struct stu { |
structure binding (C++17)
1 | struct stu { |
l-values and r-values
I-values(左值): can appear both in the right and left sides of the equations (not temp!)
r-values(右值): can appear only in the right hand side of the equations (temp.!)
1 |
|
const
to declare a value to be a r-value
cannot declare a non-const reference to a const value!
compiling
g++ -std=c++11 main.cpp -o maing++ -std=c++11 main.cpp is also OK (resulting in a.out in linux)
Stream
a general input/output abstraction for C++
![[Pasted image 20240612182503.png]]
known as iostreams!cout, cin: no need to saycerr: output errorsclog: non-critical event logging
Input streams (I)
- a way to read data from a source
- Are inherited from std::istream
- ex. reading in something from the console (std::cin)
- primary operator: >> (called the extraction operator)
Output streams (O)
- a way to write data to a destination
- Are inherited from std::ostream
- ex. writing out something to the console (std::cout)
- primary operator: << (called the insertion operator)
stringstreams
a way to treat string as streams
1 | int main() { |
what if we want the extracted_quote to be the rest? the >> only read till the blank, so we tend to use getline()!
output streams
std::endl: tells the cout stream to end the line!
also tells the stream to flush(冲厕所)
1 | int main() |
buffer: 5 ‘\n’
1 | int main() |
buffer:1 ‘\n’ 2 ‘\n’ 3 ‘\n’ 4 ‘\n’ (until it is full, it releases)5 '\n'
file systems
std::ofstream
1 | int main() |
input streams
cin reads up to white space
when cin fails: it cannot find the corresponding value until the next whitespace!
In conclusion:
- Streams are a general interface to read and write data in programs
- Input and output streams on the same source/destination type compliment each other!
- Don’t use getline() and std::cin() together, unless you really really have to!
