c++ - 用一个迭代器迭代 vector 的 vector

标签 c++ iterator containers

假设我有一个

std::vector< std::vector< int > > vvi;

我想隐藏 vvi 是 vector 的 vector 这一事实,并在其包含的所有 int 元素上创建一个迭代器,例如:

class vvi_iterator; // Iterator over std::vector< std::vector< int > >
                    // I am looking for a template of such class, 
                    // or I would need to implement it on my own.

vvi_iterator itBegin = make_vvi_iterator_begin( vvi );  // helper function
                                // that creates a vvi_iterator pointing to the 
                                // first element of the first vector

vvi_iterator itEnd   = make_vvi_iterator_end( vvi ); // helper function
                                // that creates a vvi_iterator in the "end" state
                                // (e.g. pointing behind the last element of the 
                                // last vector)


// This is how I'm going to use it:

auto itRange = boost::iterator_range<vvi_iterator>( itBegin, itEnd );

for( int& i : itRange ) {
   doSomething(i);
}

我不需要插入/删除 int 元素。

我可以使用 boost 以及其他外部库。

我可以使用 C++11,但不能使用 c++14。然而,涉及 c++14 的解决方案也会很有趣。

提前致谢。

.

.

UPD.:折叠循环对我不起作用。在我的真实用例中,我有

class A {
private:
    std::array< std::unordered_map< std::unique_ptr< SomeDataClass > > > _own_data;
}

class B {
private:
    std::vector< std::reference_wrapper< SomeDataClass > > _referenced_data;
}

并且我需要将引用s 传递给A 以及B 中的所有SomeDataClass 对象, 到其他一些类 X。我不想让 X 类知道 AB 的内部结构,我也不想把它们分开对待。

如果我没有折叠容器,我可以使用 boost::indirect_iterator:

class A {
private:
    std::array< std::unique_ptr< SomeDataClass > > _own_data;

public:
    boost::iterator_range< 
        boost::indirect_iterator<
            std::array< std::unique_ptr< SomeDataClass> >::iterator > >
    getSomeData() {
        return { boost::make_indirect_iterator( _own_data.begin() ),
                 boost::make_indirect_iterator( _own_data.end()   ) }
    }
}

class X {
private:
    doSomething( SomeDataClass& someData );

public:
    template<typename IteratorRangeType>
    processSomeData( IteratorRangeType itRange ) {
        for( auto& someData : itRange ) {
            doSomething( someData ); 
        }
    }
}



int main(int, char**) {
    A a;
    X x;
    x.processsSomeData( a.getSomeData() ); // isn't it beautiful? 
}

现在,我希望存在类似 folded_container_iterator 的东西,我希望我可以将它与 boost::indirect_iteratorboost_iterator_range 结合起来/p>

最佳答案

range-v3 , 你可以这样做

std::vector< std::vector< int > > v /* = ...*/;

for (auto e : v | ranges::view::join) {
    std::cout << e << std::endl;
}

Demo

关于c++ - 用一个迭代器迭代 vector 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43204095/

相关文章:

c++ - 忽略 iOS 应用程序中的库以针对模拟器进行编译

c++ - 将内联函数的不同实现链接到一个可执行文件中的情况如何分类?

c++ - 如何将基于迭代器的 for 循环重写为基于范围的循环 (C++11)

c++ - C++标准兼容库容器的完整接口(interface)是什么?

C++ 标准/事实上的 STL 算法包装器

docker - 容器化工具可以在本地计算机上运行吗?

c++ - 使用opencv warpaffine时如何保持白色背景

c++ - 为什么 std::vector 迭代器在 erase() 调用后失效?

rust - 实现不消耗的迭代器

c++ - 奇怪的构造函数调用