[英]Why is boost's counting_iterator const?
I need an iterator for my custom random access collection class. 我需要一个自定义随机访问集合类的迭代器。 I want to use the iterator with
std::sort
. 我想使用带有
std::sort
的迭代器。 As I'm a C++ newbee with a limited time budget, I'd like to avoid writing the whole thing myself. 因为我是一个时间预算有限的C ++新手,所以我想避免自己写整篇文章。
My iterator is basically just a simple size_t
. 我的迭代器基本上只是一个简单的
size_t
。 Therefore, I thought boost::counting_iterator
could be a good match. 因此,我认为
boost::counting_iterator
可能是一个很好的匹配。 Once I had completed the Incrementable
I had to realize that counting_iterator
defines its reference type as const Incrementable&
. 一旦我完成了
Incrementable
我必须意识到counting_iterator
将它的引用类型定义为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. 虽然我仍然对很多C ++感到困惑,但我相信这会阻止我使用带有
std::sort
的迭代器,因为const迭代器不能用于交换集合元素。
Here is the question: why does boost::counting_iterator
define its reference type as const
and, probably more important, what should I use instead? 这是一个问题:为什么
boost::counting_iterator
将其引用类型定义为const
,可能更重要的是,我应该使用什么呢?
Why does boost::counting_iterator define its reference type as const?
为什么boost :: counting_iterator将其引用类型定义为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.
简要介绍了它的文档(我不是Boost专家btw)它似乎拿着你递给它的Incrementable对象的副本 。 It then returns const references to its internal copy, to stop someone modifying its internal copy.
然后它将const引用返回到其内部副本,以阻止某人修改其内部副本。
Once I had completed the Incrementable I had to realize that counting_iterator defines its reference type as const Incrementable&.
一旦我完成了Incrementable,我必须意识到counting_iterator将它的引用类型定义为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). 是的,当取消引用时,它将返回对它所持有的Incrementable对象的常量引用,该对象本身是非常量的(因此它可以递增和递减)。
I believe this will prevent me from using the iterator with std::sort because const iterators can not be used to swap collection elements.
我相信这会阻止我使用带有std :: sort的迭代器,因为const迭代器不能用于交换集合元素。
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.
您可能只是重新使用标准迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.