为什么 const_iterator
不提供 const_iterator::base()
函数,获取对应的非常量 iterator
喜欢reverse_iterator
是吗?
考虑以下伪代码(比如几何算法):
std::container< point > universe;
auto it = std::cbegin(universe);
std::list< decltype(it) > interesting_subset = sieve(it, std::cend(universe));
auto structure = algorithm(interesting_subset);
哪里universe
是所有的输入点。在sieve()
之后-ing interesting_subset
包含 universe
子集的迭代器的成员。正在关注algorithm()
构造一个结果 structure
来自 interesting_subset
,它由对 universe
成员的引用(迭代器)组成.
最后,我想更改 point
s,包含结果 structure
(比如,转移它们)。但同样,我想保护他们在 algorithm
期间免受修改。行动,因此我使用了 std::cbegin
/std::cend
与 std::begin
相反/std::end
.最后我只有 const_iterator
引用来源 point
这是 iterator std::container< T >::const_iterator::base() const
的一个非常用例我想出现在 STL 容器中的成员函数。
最佳答案
Why does const_iterator not provide a const_iterator::base() function, to obtain corresponding non-const iterator like reverse_iterator does?
维护常量安全。提供此类功能将非常危险,正如此处已详细讨论的那样。
At the end, I want to change the points, containing into resulting structure (say, shift them). But equally I want to protect them from modyfining during algorithm action, and therefore I used std::cbegin/std::cend as opposite to std::begin/std::end. Finally I have only const_iterator references to source points.
好吧,你对 base
成员的要求是错误的。当然它会解决你的问题,但正如所说,它太危险了。让我为您改写一个问题:
If I have a
const_iterator
to an object and non-const access to the container, how do I efficiently (in constant time) get aniterator
to the referred object?
这里有一个奇特的技巧可以做到这一点:
template <typename Container, typename ConstIterator>
typename Container::iterator remove_constness(Container& c, ConstIterator it)
{
return c.erase(it, it);
}
我不认为这个把戏有任何功劳。我从https://stackoverflow.com/a/10669041/2079303找到的他们相信Howard Hinnant and Jon Kalb
如该答案的评论中所述,此技巧适用于所有标准容器,但不一定适用于所有可能符合标准的第三方容器,因为它们不需要提供 erase
。
就我个人而言,我更希望标准容器有一个非常量成员函数,可以将给定的 const_iterator
转换为 iterator
,但它们没有,所以你需要解决它。
关于c++ - 为什么 const_iterator 不像 reverse_iterator 那样提供基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33411326/