用作一维向量的多维向量迭代器? [英] Iterator for multi-dimensional vector that is used as unidimensional?

查看:167
本文介绍了用作一维向量的多维向量迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的向量:

I have a vector that looks like this:

std::vector<std::vector<MyClass>> myVector;

我想通过迭代器访问它的元素,就像它是一维向量:

And I would like to access its elements through iterators as if it was an unidimensional vector:

for (auto& x : myVector)
{
     foo(x); // x is an object of type MyClass
}

多个维度对谁透过myVector循环是透明的)

(i.e. the fact that there are multiple dimensions is transparent to whoever loops through myVector)

我有一个想法应该如何做,有一个自定义的迭代器实现,保存当前索引,向量没有更多的元素,它重置其中一个索引,并增加另一个,以便它可以开始迭代通过下一个向量等等。但我一直在试图编写这个想法,但似乎不能得到这个工作。有谁有任何想法,如何我可以实现这一点?

I have an idea of how this should be done, have a custom iterator implementation that saves current indexes so that when one of the vectors has no more elements, it resets one of the indexes and increments the other so that it can start iterating through the next vector and so on. But I have been trying to code this idea but can't seem to get this working. Does anyone have any idea of how I can possibly achieve this? Or even better, if there's any open-source project that has a similar implementation?

非常感谢。

推荐答案

使用范围/ v3

for (auto& x : myVector | ranges::view::join)
{
     foo(x); // x is an object of type MyClass&
}

演示

这篇关于用作一维向量的多维向量迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆