C++反向迭代器替代方案

发布于 2024-10-03 10:47:29 字数 470 浏览 0 评论 0原文

我正在尝试编写一个包含一些遗留代码的两遍算法。我想在一个特定的容器中移动两次,一次按顺序,一次按相反顺序。显然,我的第一个想法是使用迭代器和反向迭代器,但奇怪的是,我正在使用的容器类的设计者认为不适合定义一个工作的>reverse_iterator 用于容器(这里的reverse_iterators 不能像iterators 那样取消引用)。我已经有一个需要 reverse_iterator 的算法。

我的想法是对算法的第一部分使用第一遍迭代器,当我执行算法 push_front 时,将项目放入新容器中,然后迭代新容器。这会占用内存,这对我的应用程序来说并不重要,但让我想知道:在 C++ 中是否有任何更干净的替代方案来替代 reverse_iterators,或者我应该花时间仅使用前向来重新设计我的算法迭代器

I am attempting to write a two-pass algorithm incorporating some legacy code. I want to move through a particular container twice, once in order and once in reverse order. Obviously, my first thought was to use an iterator and a reverse_iterator, but strangely the designers of the container class I'm using did not see fit to define a working reverse_iterator for the container (reverse_iterators here cannot be dereferenced like iterators can be). I already have an algorithm that requires a reverse_iterator.

My thought is to use the first pass iterator for the first part of the algorithm, and as I perform the algorithm push_front the items into a new container, then iterate through the new container. This will take up memory, which isn't critical in my application, but made me wonder: are there any cleaner alternatives to reverse_iterators in C++, or should I take the time to rework my algorithm using only forward iterators?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后eg是否自 2024-10-10 10:47:29

如果需要以相反的顺序迭代容器的元素,则不一定需要使用反向迭代器。

如果容器有双向迭代器,那么您可以使用普通迭代器并使用 --it 来从 end() 迭代到 begin()使用++itbegin()迭代到end()

由于这有点棘手,您可以使用 std::reverse_iterator 包装器将普通迭代器转换为反向迭代器(这基本上交换了 ++- - 并封装了使其正常工作所需的技巧)。

如果容器没有双向迭代器,则意味着不可能以相反的顺序迭代容器的元素,在这种情况下,您需要重写算法或使用不同的容器。

任何具有双向迭代器的容器,都应该提供反向迭代器功能;这是STL 和C++ 标准库“容器”概念的一部分。

If you need to iterate over the elements of a container in reverse order, you don't necessarily need to use a reverse iterator.

If the container has bidirectional iterators, then you can use ordinary iterators and use --it to iterate from end() to begin() instead of using ++it to iterate from begin() to end().

Since this is a bit tricky, you can use the std::reverse_iterator wrapper to convert an ordinary iterator into a reverse iterator (this basically swaps ++ and -- and encapsulates the trickery required to get this to work).

If the container doesn't have bidirectional iterators then that means it's impossible to iterate over the elements of the container in reverse order, in which case you would need either to rewrite your algorithm or to use a different container.

Any container that has bidirectional iterators, it should provide reverse iterator functionality; this is part of the STL and C++ Standard Library "Container" concept.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文