-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathConceptualExample01.cpp
More file actions
91 lines (72 loc) · 2.26 KB
/
ConceptualExample01.cpp
File metadata and controls
91 lines (72 loc) · 2.26 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// ===========================================================================
// ConceptualExample01.cpp // Iterator Pattern // Standard C++
// ===========================================================================
#include <iostream>
#include <vector>
#include <print>
class MyContainer
{
public:
using value_type = int;
using difference_type = std::ptrdiff_t;
using iterator_category = std::vector<int>::iterator;
using pointer = value_type*;
using reference = value_type&;
private:
std::vector<int> m_data;
public:
MyContainer(const std::initializer_list<int>& values) : m_data(values) {}
// nested iterator class
class Iterator {
private:
std::vector<int>::iterator m_iter;
public:
// c'tor
Iterator(std::vector<int>::iterator it) : m_iter{ it } {}
// dereference operator
int& operator*() { return *m_iter; }
// pre-increment operator
Iterator& operator++() {
++m_iter;
return *this;
}
// post-increment operator
Iterator operator++(int) {
Iterator temp = *this;
++(*this);
return temp;
}
// equality comparison
bool operator==(const Iterator& other) const {
return m_iter == other.m_iter;
}
// inequality comparison
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
};
using iterator = Iterator;
public:
// begin iterator
Iterator begin() noexcept { return Iterator{ m_data.begin() }; }
// end iterator
Iterator end() noexcept { return Iterator{ m_data.end() }; }
};
void test_conceptual_example_01()
{
MyContainer container { 1, 2, 3, 4, 5 };
for (MyContainer::iterator it = container.begin(); it != container.end(); ++it) {
std::print("{} ", *it);
}
std::println();
for (auto elem : container) {
std::print("{} ", elem);
}
std::println();
for (const auto& elem : container) {
std::print("{} ", elem);
}
}
// ===========================================================================
// End-of-File
// ===========================================================================