c++ - 为什么 const_iterator 不像 reverse_iterator 那样提供基类?

标签 c++ stl iterator containers const-iterator

为什么 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::cendstd::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 an iterator 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/

相关文章:

c++ - 是什么让 C++ 程序只能是 64 位或受机器限制?

java - For-each 与迭代器。哪个会是更好的选择

Scala函数错误: type mismatch

c++ - 如何在给定两点的情况下沿直线移动物体?

c++ - 带有用户定义数组的 for 循环 - C++

c++ - 在 65536 位置访问迭代器的指针运算符导致段错误

c++ - 在 C++ 中将元素添加到 vector 之前是否需要检查容量?

c++ - 在构造函数中调用列表上的迭代器会更改其最终值吗?

c++ - 为什么在预期 T 或 T& 时定义重载运算符的任意返回类型是合法的

C++ 字符串使用分配的最大缓冲区?