-
Notifications
You must be signed in to change notification settings - Fork 0
/
09-containers.cc
72 lines (61 loc) · 1.53 KB
/
09-containers.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// Program
// Find a pair in std::vector
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -o 09-containers 09-containers.cc
//
// Execution
// ./09-containers
//
#include <iostream>
#include <cstdint>
#include <cassert>
#include <vector>
#include <algorithm>
#include <optional>
using element = std::pair<uint32_t, float>;
// Checks if the container contains given element
bool contains(const std::vector<element>& vec, uint32_t key) {
auto it = std::find_if(vec.begin(), vec.end(), [key](const element& elem) {
return (elem.first == key);
});
return (it != vec.end());
}
// Checks if the container contains given element
std::optional<element> find(const std::vector<element>& vec, uint32_t key) {
auto it = std::find_if(vec.begin(), vec.end(), [key](const element& elem) {
return (elem.first == key);
});
if (it == vec.end()) {
return std::nullopt;
}
int distance = std::distance(vec.begin(), it);
return vec.at(distance);
}
//
// Entry function
//
int main() {
std::vector<element> vec {
{1, 1.0f},
{2, 2.0f},
{3, 3.0f},
};
// Check whether key is in container
assert(contains(vec, 1) == true);
assert(contains(vec, 3) == true);
assert(contains(vec, 5) == false);
// Find pair in container
for (auto key: {1, 2, 4, 5}) {
auto f = find(vec, key);
if (f.has_value()) {
auto pair = f.value();
std::cout << key << " -> " << "{" << pair.first << "," << pair.second << "}\n";
}
else {
std::cout << key << " -> " << "{ not found }\n";
}
}
return 0;
}