合并具有交替模式的两个STL向量 [英] Merge two STL vectors with an alternation pattern

查看:199
本文介绍了合并具有交替模式的两个STL向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个STL向量A和B,需要将它们合并成第三个,其中的元素应该以某种方式排序,输出向量中的每个第n个元素应该是向量B.我当前的代码看起来东西像这样:

I have two STL vectors A and B and need to merge them into a third one, where the elements should be ordered in a way, that every nth element in the output vector should be of vector B. My current code looks something like this:

std::vector<int> a(10, 4);
std::vector<int> b(10, 8);
std::vector<int> c;
static const std::size_t STEP(3);

std::vector<int>::const_iterator bIt = b.begin();
for(std::vector<int>::const_iterator aIt = a.begin();
    aIt != a.end(); ++aIt)
{
    c.push_back(*aIt);
    if((c.size() + 1) % STEP == 0)
    {
        c.push_back(*bIt);
        ++bIt; //assume b is large enough
    }
}

看起来像:
4 4 8 4 4 8 ...

The vector c now looks like: 4 4 8 4 4 8 ...

这很好,但我很好奇,如果没有更优雅的解决方案。是否有任何方式使用STL算法而不是我的手写循环?

This works fine, but I'm curious if there isn't a more elegant solution. Is there any way use a STL algorithm instead of my hand-written loops?

推荐答案

< algorithm> 。避免循环将需要一个自定义的迭代器。

This is too specialized to be covered directly by <algorithm>. Avoiding the loop will require a custom iterator.

template< typename I1, typename I2 >
struct interleave_iterator
    : std::iterator< forward_iterator_tag, typename I1::value_type > {
    using typename I1::value_type;

    I1 i1;
    I2 i2;
    size_t cnt, stride;

    interleave_iterator( I1 in1, I2 in2, size_t in_stride=0, size_t in_off=0 )
        : i1( in1 ), i2( in2 ), cnt( in_off ), stride( in_stride ) {}

    value_type &operator*() const { return cnt? * i1 : * i2; }
    interleave_iterator &operator++() {
        if ( ++ cnt == stride ) {
            cnt = 0;
            ++ i2;
        } else ++ i1;
        return *this;
    }
    value_type *operator->() const
        { return cnt? i1.operator->() : i2.operator->(); }

    interleave_iterator &operator++(int)
        { interleave_iterator r = *this; ++ *this; return r; }

    friend bool operator==
        ( interleave_iterator const &lhs, interleave_iterator const &rhs )
        { return lhs.i1 == rhs.i1 && lhs.i2 == rhs.i2; }
    friend bool operator!=
        ( interleave_iterator const &lhs, interleave_iterator const &rhs )
        { return ! ( lhs == rhs ); }
};

我觉得有点过分。

这篇关于合并具有交替模式的两个STL向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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