【问题标题】:Indexed subset iterator in Boost C++Boost C++中的索引子集迭代器
【发布时间】:2013-11-13 13:48:47
【问题描述】:

我的容器是随机访问的,例如标准::向量。我需要容器的“索引子集迭代器”。我编了这个名字。这个想法是:

我的容器的一个子集由一组索引给出,例如[0, 4, 5, 7] (我的容器的大小大于 7),我想要一个迭代这个子集的迭代器。

以下是伪代码:

std::vector<std::string> v = boost::assign::list_of("Aa")("Bb")("Cc")("Dd")("Ee");
std::vector<int> subsetIndex = boost::assign::list_of(0)(2)(3);
IndexedSubsetIterator subsetIterator = IndexedSubsetIterator(v.begin(), subsetIndex);  // or templated version
std::vector<std::string> subset;
boost::push_back(subset ubsetIterator);

我想知道在 STL 或 boost 中是否有一种简单的方法可以做到这一点?示例代码请赞赏。

非常感谢。

【问题讨论】:

    标签: c++ boost iterator


    【解决方案1】:

    这就是来自 Boost 的 permutation_iterator 的用途。您构造一个从迭代器到源的迭代器和一个从迭代器到索引容器的迭代器。这是一个可运行的示例:

    #include <vector>
    #include <iostream>
    #include <algorithm>
    #include <boost/iterator/permutation_iterator.hpp>
    #include <boost/assign/list_of.hpp>
    
    int main()
    {
        std::vector<std::string> v =
            boost::assign::list_of("Aa")("Bb")("Cc")("Dd")("Ee");
        std::vector<int> subsetIndex =
            boost::assign::list_of(0)(2)(3);
    
        auto it_begin =
            boost::make_permutation_iterator(v.begin(), subsetIndex.begin());
        auto it_end =
            boost::make_permutation_iterator(v.end(), subsetIndex.end());
    
        std::vector<std::string> subset;
        std::copy(it_begin, it_end, std::back_inserter(subset));
    
        for (const auto& s : subset) std::cout << s << '\n';
    }
    

    输出:

    Aa
    Cc
    Dd
    

    【讨论】:

    • 正是我想要的。谢谢。
    猜你喜欢
    • 2015-04-03
    • 2011-05-12
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    相关资源
    最近更新 更多