Some languages standardize syntax. C++ and Python are notable examples.
C++ C++ implements iterators with the semantics of
pointers in that language. In C++, a class can overload all of the pointer operations, so an iterator can be implemented that acts more or less like a pointer, complete with dereference, increment, and decrement. This has the advantage that C++ algorithms such as std::sort can immediately be applied to plain old memory buffers, and that there is no new syntax to learn. However, it requires an "end" iterator to test for equality, rather than allowing an iterator to know that it has reached the end. In C++ language, we say that an iterator models the iterator
concept. This C++23 implementation is based on chapter "Generalizing vector yet again". import std; template using InitializerList = std::initializer_list; using OutOfRangeException = std::out_of_range; template using UniquePtr = std::unique_ptr; class DoubleVector { private: UniquePtr elements; size_t listSize; public: using Iterator = double*;
nodiscard Iterator begin() const noexcept { return elements; }
nodiscard Iterator end() const noexcept { return elements + listSize; } DoubleVector(InitializerList list): elements{std::make_unique(list.size())}, listSize{list.size()} { double* p = elements; for (auto i = list.begin(); i != list.end(); ++i, ++p) { *p = *i; } // alternatively implemented with // std::ranges::copy(list, elements.get()) } ~DoubleVector() = default;
nodiscard size_t size() const noexcept { return listSize; }
nodiscard double& operator[](size_t n) { if (n >= listSize) { throw OutOfRangeException("DoubleVector::operator[] out of range!"); } return elements[n]; } DoubleVector(const DoubleVector&) = delete; // disable copy construction DoubleVector& operator=(const DoubleVector&) = delete; // disable copy assignment }; int main(int argc, char* argv[]) { DoubleVector v = {1.1 * 1.1, 2.2 * 2.2}; for (const double& x : v) { std::println("{}", x); } for (size_t i = v.begin(); i != v.end(); ++i) { std::println("{}", *i); } for (size_t i = 0; i The program output is 1.21 4.84 1.21 4.84 1.21 4.84 terminate called after throwing an instance of 'OutOfRangeException' what(): DoubleVector::operator[] out of range! == See also ==