将多个 std::list 迭代器压缩在一起
使用 boost 库,可以使用 zip 将已知数量的迭代器压缩在一起迭代器,但是当要压缩的迭代器的数量直到运行时才知道时该怎么办?
为了扩展一点,我有一个大小相同的列表列表,我需要将每个索引处的所有值分组在一起,并将它们输入到另一个操作中。现在这都是手动的,我觉得应该有更好的方法。
示例:
假设我有 3 个列表:
- [1, 2, 3, 4, 5]
- [11, 12, 13, 14, 15]
- [21, 22, 23, 24, 25]
我需要将这些列表转换为:
- [1, 11, 12]
- [2, 12, 22]
- [3, 13, 23]
- [4, 14, 24]
- ...等等
我不知道运行时输入中有多少列表。
Using the boost library it is possible to zip together a known number of iterators using a zip iterator, but what about when the number of iterators to be zipped is not known until runtime?
To expand a little bit, I have a list of lists that are all the same size, and I need to group together all the values at each each index and feed them into another operation. Right now this is all manual, and I feel like there should be a better way.
Example:
Say I have 3 lists:
- [1, 2, 3, 4, 5]
- [11, 12, 13, 14, 15]
- [21, 22, 23, 24, 25]
I need to transform these lists into:
- [1, 11, 12]
- [2, 12, 22]
- [3, 13, 23]
- [4, 14, 24]
- ... etc
I do not know how many lists are in the input until runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,在花了近 1/2 小时之后,我想出了这个可以进一步改进的
dynamic_zip_iterator
类,使其看起来像 STL 式的迭代器。到目前为止,它非常具体,因为我已经在其中硬编码了std::list
,您可以用std::vector
替换它,或者可以使其更通用:无论如何,看看它:
使用它你的问题简化为这个功能:
测试代码:
输出:
在线演示: http://ideone .com/3FJu1
Alright after spending almost 1/2 hour, I came up with this
dynamic_zip_iterator
class which can be further improved, to make it look like STL-like iterators. As of now, it's very specific, as I've hardcodedstd::list
in it which you can replace withstd::vector
or can make even more generic:Anyway, have a look at it:
Using it your problem reduces to this function:
Test code:
Output:
Online demo : http://ideone.com/3FJu1
我很确定今天不存在这样的事情。但为什么不创建一个非常简单的迭代器元素列表呢?我确信那会成功的!
为
for
语句的所有 3 部分创建一个函数 -->开始、结束、增量这应该足够了!下面有更多细节。
begin : (对列表列表的常量引用,对迭代器的空列表的引用) -->使用 begin() 为每个子列表构造迭代器列表
end : (const ref to list of iterators, const ref to list of list) -->如果一个迭代器位于其列表的末尾,则为 true
increment : (参考迭代器列表) -->增加列表中的每个迭代器
I am pretty sure nothing exists today for that. But why not create a very simple list of iterator elements ? That would do the trick, i am sure !
Create a function for all 3 parts of the
for
statement --> begin, end, incrementAnd that should be enough ! A bit more detail below.
begin : (const ref to list of lists, reference to empty list of iterators) --> construct the iterator list using begin() for each sublist
end : (const ref to list of iterators, const ref to list of lists) --> true if one iterator is at the end of its list
increment : (ref to list of iterators) --> increment every iterator in the list