Browse Source

Solved Lab2

master
Kenneth Bruen 3 years ago
parent
commit
7abc7d89dd
Signed by: kbruen
GPG Key ID: CB77B9FE7F902176
  1. 32
      Lab2/README.md
  2. 47
      Lab2/slide12.cpp
  3. 47
      Lab2/slide13.cpp
  4. 1
      README.md

32
Lab2/README.md

@ -0,0 +1,32 @@
# CCIoT Homework Lab 2
## Slide 12
### Problem
Try the following:
1. Create a vector of whatever type you like (minimum length of 10);
2. Print it’s content;
3. Erase the odd elements;
4. Replace the first element and the last element with another value;
5. Create a rule that erases the 5th element from the vector;
6. Use cppreference in the meantime ☺
### Solution
See [slide12.cpp](./slide12.cpp).
## Slide 13
### Problem
Try the same stuff with std::list, observe the differences.
### Solution
See [slide13.cpp](./slide13.cpp).
The difference observed is at line 38.
Because `std::list` has a bidirectional iterator, not a random access one, skipping 4 elements cannot be done.
Instead, I had to use `std::next` in order to advance the iterator 4 times separately in order to find the 5th element and erase it.

47
Lab2/slide12.cpp

@ -0,0 +1,47 @@
#include <iostream>
#include <vector>
// 2.
template <class T>
void printEnumerable(const T &enumerable) {
bool first = true;
for (const auto& item : enumerable) {
if (first) first = false;
else std::cout << ", ";
std::cout << item;
}
std::cout << std::endl;
}
// 4.
template <class T, typename V>
void replaceFirstLast(T& enumerable, const V& newValue) {
*std::begin(enumerable) = newValue;
*std::rbegin(enumerable) = newValue;
}
// 5.
template <class T>
void erase5th(T& enumerable) {
enumerable.erase(std::begin(enumerable) + 4);
}
int main() {
// 1.
std::vector<int> v {8, 4, 6, 1, 5, 3, 9, 5, 8, 123, 1, 2, 31, 24, 124, 12, 42, 131};
// 2.
printEnumerable(v);
// 4.
replaceFirstLast(v, 7);
// 5.
erase5th(v);
// Print again to see changes
printEnumerable(v);
return 0;
}

47
Lab2/slide13.cpp

@ -0,0 +1,47 @@
#include <iostream>
#include <list>
// 2.
template <class T>
void printEnumerable(const T &enumerable) {
bool first = true;
for (const auto& item : enumerable) {
if (first) first = false;
else std::cout << ", ";
std::cout << item;
}
std::cout << std::endl;
}
// 4.
template <class T, typename V>
void replaceFirstLast(T& enumerable, const V& newValue) {
*std::begin(enumerable) = newValue;
*std::rbegin(enumerable) = newValue;
}
// 5.
template <class T>
void erase5th(T& enumerable) {
enumerable.erase(std::next(std::begin(enumerable), 4));
}
int main() {
// 1.
std::list<int> v {8, 4, 6, 1, 5, 3, 9, 5, 8, 123, 1, 2, 31, 24, 124, 12, 42, 131};
// 2.
printEnumerable(v);
// 4.
replaceFirstLast(v, 7);
// 5.
erase5th(v);
// Print again to see changes
printEnumerable(v);
return 0;
}

1
README.md

@ -1,3 +1,4 @@
# CCIoT Homework # CCIoT Homework
- [Lab1](./Lab1/) - [Lab1](./Lab1/)
- [Lab2](./Lab2/)

Loading…
Cancel
Save