Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on When to use custom iterators versus pointers

Parent

When to use custom iterators versus pointers

+4
−0

I am working on a toy project where I have a container for which I would like to write an iterator that iterates over the values in the container. Because the values are stored in a (c-style) array, this would look something like this:

class MyClass {
	int _data[10] {};
public:
	class MyIterator;

	MyIterator begin();
	MyIterator end();
};

class MyClass::MyIterator final {
	int* _position {};
public:
	using iterator_category = std::contiguous_iterator_tag;
	using value_type = int;
	using difference_type = std::ptrdiff_t;
	using pointer = value_type*;
	using reference = value_type&;

	explicit MyIterator(int* from) : _position { from } {}
	reference operator*() const { return *_position; }
	pointer operator->() const { return _position; }
	MyIterator& operator++() { ++_position; return *this; }
	MyIterator operator++(int) { MyIterator tmp { *this }; operator++(); return tmp; }
	MyIterator& operator--() { --_position; return *this; }
	MyIterator operator--(int) { MyIterator tmp { *this }; operator--(); return tmp; }
	MyIterator operator += (const difference_type& n) { _position += n; return *this; }
	MyIterator operator -= (const difference_type& n) { _position -= n; return *this; }
	MyIterator operator[](const difference_type& n) { return MyIterator(_position + n); }

	friend auto operator<=>(MyIterator, MyIterator) = default;
	friend auto operator+(MyIterator it, difference_type n) { MyIterator result { it }; result += n; return result; }
	friend auto operator-(MyIterator it, difference_type n) { MyIterator result { it }; result -= n; return result; }
	friend auto operator+(difference_type n, MyIterator it) { return it + n; }
};

MyClass::MyIterator MyClass::begin() {
	return MyClass::MyIterator(&_data[0]);
}

MyClass::MyIterator MyClass::end() {
	return MyClass::MyIterator(&_data[0] + 10);
}

However, while writing this code, I couldn't help but notice that I am essentially writing a wrapper around pointer arithmetic. Instead of writing a custom iterator, everything seems to work just as well when using the following, much more concise code:

class MyClass2 {
	int _data[10] {};
public:
	using MyIterator = int*;

	MyIterator begin();
	MyIterator end();
};

MyClass2::MyIterator MyClass2::begin() {
	return &_data[0];
}

MyClass2::MyIterator MyClass2::end() {
	return &_data[0] + 10;
}

I understand that using a raw pointer as an iterator is enabled by the specialisation of std::iterator_traits. So why would/should I bother encapsulating the iterator in a full class with trivial code when using a raw pointer works just as well?

I do understand that there are scenarios where iterators require more complexity than plain pointer arithmetic. However, I suspect that most iterators can be written as iterating over an array. Is there any reason to wrap an iterator for array-like classes in a custom iterator class? If yes, is there any class in the standard library that implements this? I could only find std::iterator, but this is deprecated and doesn't really implement anything...

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

2 comment threads

This all stuff actually looks like re-inventing the wheel to me. You might do that for practicing pur... (1 comment)
Wrapper (4 comments)
Post
+0
−0

However, I suspect that most iterators can be written as iterating over an array.

From my experience, I wouldn't expect this to be the case. From the standard library containers, only std::vector and std::array can work with iterators implemented as pointers. All the other containers have internal structures different from a C-style array.

After all, a pointer is by definition a contiguous_iterator, and most containers (not just std ones) are structured such that they don't (and can't) support contiguous iterators.

I've written many various iterator classes; mostly over ranges, but some over containers too. Not once was there a single contiguous array in the underlying the data structure such that a pointer could be used in place of the iterator.

Is there any reason to wrap an iterator for array-like classes in a custom iterator class?

Nothing major. If I was writing a container/range that could use a pointer as an iterator, I'd probably use it and invest the saved development time elsewhere.

One possible reason to wrap a pointer in a class is that you can introduce custom behaviour, such as assert-based bounds checking which can catch some bugs in debug builds without slowing down production code.

If yes, is there any class in the standard library that implements this?

I am not aware of anything in the standard library. However, when writing your own iterators, it's well worth it to look into the Boost.Iterator library; in particular, you should consider checking out the boost::iterator_facade class template.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

1 comment thread

Underlying representation (4 comments)
Underlying representation
Lundin‭ wrote 8 months ago · edited 8 months ago

Now of course, the standard doesn't mandate how things are implemented "backstage". There's probably no good performance reason why a lot of things like std::set or std::map wouldn't be implemented as some sort of C style arrays. Namely because on most systems, arrays have superior performance for iteration. Whereas linked lists, trees, hash tables, graphs etc have awful iteration performance as well as poor allocation speed. What you gain from quick swapping, you may lose in iteration speed. "STL" was created at a time when cache memories and branch prediction were still new and fancy things. Just as the C standard lib, most of the C++ standard lib was designed at a whim rather than with care about good programming practices. Stroustrup kept blaming compilers, saying there was no good reason why std::vector would be slower than C arrays. Except it always was. And when std::array was released, he suddenly hushed up about std::vector.

Lundin‭ wrote 8 months ago

It's the same kind of argument as why computer scientists are still being all smug about binary search over brute force linear iteration, even though in many situations, the latter is probably way faster on modern computers. Algorithm theory has not quite kept up with computer hardware development and many computer scientists are not great programmers for that reason.

Angew‭ wrote 8 months ago

The good programmer has as many tools in their toolbox as they can get, and use the best one for the job, evaluating simplicity, performance, maintainability, reliability, etc. all jointly. Shoehorning everything into std::vector is just as bad as using a std::map whose maximum size will never exceed 10.

Lundin‭ wrote 8 months ago

Except the application layer programmer typically won't have a clue about how the various containers are implemented internally. Which has always been a big problem with C++, std::string or std::vector silently using heap allocation etc. And if you don't know how they are implemented, you can't know how well they will perform, short of trial & error benchmarking.