typecode
C++Smart Pointers/main.cpp
1#include <memory>
2#include <vector>
3#include <string>
4#include <algorithm>
5#include <optional>
6
7struct Sensor {
8 std::string name;
9 double value;
10 bool active;
11};
12
13class SensorNetwork {
14 std::vector<std::unique_ptr<Sensor>> sensors_;
15
16public:
17 void add(std::string name, double initial) {
18 auto sensor = std::make_unique<Sensor>(
19 Sensor{std::move(name), initial, true}
20 );
21 sensors_.push_back(std::move(sensor));
22 }
23
24 std::optional<double> read(const std::string& name) const {
25 auto it = std::find_if(
26 sensors_.begin(), sensors_.end(),
27 [&name](const auto& s) {
28 return s->name == name && s->active;
29 }
30 );
31 if (it != sensors_.end()) {
32 return (*it)->value;
33 }
34 return std::nullopt;
35 }
36
37 void update(const std::string& name, double val) {
38 for (auto& sensor : sensors_) {
39 if (sensor->name == name) {
40 sensor->value = val;
41 return;
42 }
43 }
44 }
45
46 std::vector<std::string> active_names() const {
47 std::vector<std::string> result;
48 for (const auto& s : sensors_) {
49 if (s->active) {
50 result.push_back(s->name);
51 }
52 }
53 return result;
54 }
55
56 size_t count() const { return sensors_.size(); }
57
58 void deactivate(const std::string& name) {
59 for (auto& sensor : sensors_) {
60 if (sensor->name == name) {
61 sensor->active = false;
62 return;
63 }
64 }
65 }
66};
0WPM
100%Accuracy
00:00Time
0%
Progress