Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is boost's counting_iterator const?

Tags:

c++

boost

I need an iterator for my custom random access collection class. I want to use the iterator with std::sort. As I'm a C++ newbee with a limited time budget, I'd like to avoid writing the whole thing myself.

My iterator is basically just a simple size_t. Therefore, I thought boost::counting_iterator could be a good match. Once I had completed the Incrementable I had to realize that counting_iterator defines its reference type as const Incrementable&.

Although I'm still confused by a lot of C++, I believe this will prevent me from using the iterator with std::sort because const iterators can not be used to swap collection elements.

Here is the question: why does boost::counting_iterator define its reference type as const and, probably more important, what should I use instead?

like image 927
Johannes Luong Avatar asked Nov 08 '22 11:11

Johannes Luong


1 Answers

Why does boost::counting_iterator define its reference type as const?

Its purpose, as described here, is to fill arrays with an object that is itself incremented when the iterator is incremented. Having had a brief look through its docs (I'm no Boost expert btw) it seems to hold a copy of the Incrementable object you hand it. It then returns const references to its internal copy, to stop someone modifying its internal copy.

Once I had completed the Incrementable I had to realize that counting_iterator defines its reference type as const Incrementable&.

Yes, when dereferenced it will return a constant reference to the Incrementable object that it holds, which is itself non-constant (hence it can be incremented and decremented).

I believe this will prevent me from using the iterator with std::sort because const iterators can not be used to swap collection elements.

Correct :) Under-the-hood a swap looks like

using T = size_t;
T tmp = a;
a = b;    // requires a to be non-constant
b = tmp;  // requires b to be non-constant

What should I use instead?

Depends on your container. An iterator to a container should contain a pointer to an element in the container. You can probably just re purpose a standard iterator.

like image 98
Judge Avatar answered Nov 14 '22 21:11

Judge