L2.Structures
约 268 个字 60 行代码 预计阅读时间 2 分钟
Aggregate Structures¶
A structure is a collection of named variables.
Structures are similar to classes, but all members in a structure are public by default(date,cases,deaths
).
You can access each member using the dot(.) operator.
C++ | |
---|---|
We have two special structs in C++ called pair
and tuple
.
std::pair
has two members named first
and second
.
std::tuple
has multiple members.
Note
pair
appears a lot in C++ standard library while tuple
is rarely used.So don't talk much about tuple
.
Any type of data can be given to pair
and tuple
.But the name of the members are always first
and second
.
C++ | |
---|---|
std::array and std::vector are collections of homogeneous type.
C++ | |
---|---|
A std::array
has a fixed size 2 and fixed type int
.You can access the elements using the subscript operator []
.
A std::vector
has a dynamic size and you can add elements using push_back()
.
Auto and Structured Binding¶
auto
keyword is used to deduce the type of a variable.
C++ | |
---|---|
Answers
a = int
b = double
c = char
d = char*
e = std::string
f = std::pair
g = std::initializer_list
h = only konwn by compiler
When and Why to Use Auto¶
When¶
- You don't care about the exact type(iterators).
- When its type is clear from context(templates).
- When you can't figure out the type(lambdas).
- Avoid using auto for return values(exception: generic programming).
Why¶
- Correctness: no implict conversions,uninitialized variables.
- Flexibility: code easily modifiable if type changes need to be made.
- Powerful: very important when we get to templates.
- Modern IDE's can infer a type simply by hovering your cursor over any auto, so readability is not an issue.
C++ | |
---|---|
Exercise: quadratic solver¶
Given three real numbers a,b,c, find the roots of the quadratic equation ax^2 + bx + c = 0.