Construction a vector from the concatenation of 2 vectors

后端 未结 6 472
梦谈多话
梦谈多话 2021-01-12 22:45

Is there a way to construct a vector as the concatenation of 2 vectors (Other than creating a helper function?)

For example:



        
6条回答
  •  轮回少年
    2021-01-12 23:20

    I came across this question looking for the same thing, and hoping there was an easier way than the one I came up with... seems like there isn't.

    So, some iterator trickery should do it if you don't mind a helper template class:

    #include 
    #include 
    
    template
    class concat
    {
    public:
        using value_type = typename std::vector::const_iterator::value_type;
        using difference_type = typename std::vector::const_iterator::difference_type;
        using reference = typename std::vector::const_iterator::reference;
        using pointer = typename std::vector::const_iterator::pointer;
        using iterator_category = std::forward_iterator_tag;
        concat(
            const std::vector& first,
            const std::vector& last,
            const typename std::vector::const_iterator& iterator) : 
                mFirst{first},
                mLast{last},
                mIterator{iterator}{}
        bool operator!= ( const concat& i ) const
        {
            return mIterator != i.mIterator;
        }
        concat& operator++()
        {
            ++mIterator;
            if(mIterator==mFirst.end())
            {
                mIterator = mLast.begin();
            }
            return *this;
        }
        reference operator*() const
        {
            return *mIterator;
        }
    private:
        const std::vector& mFirst;
        const std::vector& mLast;
        typename std::vector::const_iterator mIterator;
    };
    
    int main()
    {
        const std::vector first{0,1,2,3,4};
        const std::vector last{5,6,7,8,9};
        const std::vector concatenated(
            concat(first,last,first.begin()),
            concat(first,last,last.end()));
        for(auto i: concatenated)
        {
            std::cout << i << std::endl;
        }
        return 0;
    }
    

    You may have to implement operator++(int) or operator== depending on how your STL implements the InputIterator constructor, this is the minimal iterator code example I could come up with for MingW GCC.

    Have Fun! :)

提交回复
热议问题