Implementing an iterator over combinations of many vectors

前端 未结 1 839
栀梦
栀梦 2021-01-16 14:05

I am working on a problem that requires iterating over all combinations of elements of K vectors taken one at a time. So for example for K=2 vector

相关标签:
1条回答
  • 2021-01-16 14:57

    Why would you like to use custom iterators? One could instead implement a very simple class that will iterate through all combinations:

    class Combinator
    {
    public:
        Combinator(std::vector<std::vector<int> >& vectors)
            : m_vectors(vectors)
        {
            m_combination.reserve(m_vectors.size());
            for(auto& v : m_vectors)
                m_combination.push_back(v.begin());
        }
    
        bool next()
        {
            // iterate through vectors in reverse order
            for(long long i = m_vectors.size() - 1; i >= 0; --i)
            {
                std::vector<int>& v = m_vectors[i];
                std::vector<int>::iterator& it = m_combination[i];
    
                if(++it != v.end())
                    return true;
                it = v.begin();
            }
            return false;
        }
    
        std::vector<std::vector<int>::iterator> combination() const
        {
            return m_combination;
        }
    
    private:
        std::vector<std::vector<int> >& m_vectors; // reference to data
        std::vector<std::vector<int>::iterator> m_combination;
    };
    

    Live Demo

    UPDATE: If you would still like to use iterators, I suggest iterating over combinations. One can put all the combinations from Combinator into a container and then work with container's own iterators. In my opinion it's a cleaner solution. The only drawback is the extra-memory needed to store all combinations explicitly.

    0 讨论(0)
提交回复
热议问题