mirror of
https://github.com/dancojocaru2000/y3s2-cciot-hw.git
synced 2025-02-22 17:09:35 +02:00
Initial commit, solve Lab1 Slide11
This commit is contained in:
commit
ef5f055695
3 changed files with 101 additions and 0 deletions
28
Lab1/README.md
Normal file
28
Lab1/README.md
Normal file
|
@ -0,0 +1,28 @@
|
|||
# CCIoT Homework Lab 1
|
||||
|
||||
## Slide 11
|
||||
|
||||
### Problem
|
||||
|
||||
```cpp
|
||||
class Human
|
||||
{
|
||||
public:
|
||||
Human();
|
||||
~Human();
|
||||
std::string name;
|
||||
int age;
|
||||
};
|
||||
```
|
||||
|
||||
Try this:
|
||||
|
||||
1. Create 4 humans.
|
||||
2. Give them names and ages.
|
||||
3. Retrieve the data from all humans and print it to the screen.
|
||||
4. Print the data for the youngest human.
|
||||
5. Print all humans’ names in descending order by their names.
|
||||
|
||||
### Solution
|
||||
|
||||
See [slide11.cpp](./slide11.cpp).
|
70
Lab1/slide11.cpp
Normal file
70
Lab1/slide11.cpp
Normal file
|
@ -0,0 +1,70 @@
|
|||
// For std::string
|
||||
#include <string>
|
||||
// For std::cout
|
||||
#include <iostream>
|
||||
// For std::sort
|
||||
#include <algorithm>
|
||||
|
||||
class Human
|
||||
{
|
||||
public:
|
||||
Human();
|
||||
~Human();
|
||||
std::string name;
|
||||
int age;
|
||||
};
|
||||
|
||||
// Implementation
|
||||
Human::Human() : name{}, age{} {}
|
||||
Human::~Human() {}
|
||||
|
||||
int main() {
|
||||
// 1. Create 4 humans
|
||||
Human humans[4];
|
||||
|
||||
// 2. Give them names and ages.
|
||||
humans[0].name = "Joe";
|
||||
humans[0].age = 18;
|
||||
humans[1].name = "Jane";
|
||||
humans[1].age = 19;
|
||||
humans[2].name = "Jim";
|
||||
humans[2].age = 20;
|
||||
humans[3].name = "John";
|
||||
humans[3].age = 21;
|
||||
|
||||
// 3. Retrieve the data from all humans
|
||||
// and print it to the screen.
|
||||
for (int i = 0; i < 4; i++) {
|
||||
std::cout
|
||||
<< "name=" << humans[i].name
|
||||
<< ", age=" << humans[i].age
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
// 4. Print the data for the youngest
|
||||
// human.
|
||||
Human& youngest = humans[0];
|
||||
for (int i = 1; i < 4; i++) {
|
||||
if (humans[i].age < youngest.age) {
|
||||
youngest = humans[i];
|
||||
}
|
||||
}
|
||||
std::cout
|
||||
<< "Youngest:"
|
||||
<< " name=" << youngest.name
|
||||
<< ", age=" << youngest.age
|
||||
<< std::endl;
|
||||
|
||||
// 5. Print all humans' names in
|
||||
// descending order by their
|
||||
// names.
|
||||
std::sort(humans, humans + 4, [](const Human &h1, const Human &h2) {
|
||||
return h1.name <= h2.name;
|
||||
});
|
||||
for (int i = 0; i < 4; i++) {
|
||||
std::cout << humans[i].name << ", ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
3
README.md
Normal file
3
README.md
Normal file
|
@ -0,0 +1,3 @@
|
|||
# CCIoT Homework
|
||||
|
||||
- [Lab1](./Lab1/)
|
Loading…
Add table
Reference in a new issue