什么将是一个很好的实现iota_n的(缺少的STL算法) [英] What would be a good implementation of iota_n (missing algorithm from the STL)

查看:213
本文介绍了什么将是一个很好的实现iota_n的(缺少的STL算法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++ 11中,STL现在有一个的std ::丝毫函数(见的引用)。相反,的std :: fill_n 的std :: generate_n ,没有 STD: :iota_n ,但是。什么将是一个很好的实现是什么?直接环路(备选方案1)或委派的std :: generate_n 用一个简单的lambda EX pression(备选2)?

With C++11, the STL has now a std::iota function (see a reference). In contrast to std::fill_n, std::generate_n, there is no std::iota_n, however. What would be a good implementation for that? A direct loop (alternative 1) or delegation to std::generate_n with a simple lambda expression (alternative 2)?

方案1)

template<class OutputIterator, class Size, class T>
OutputIterator iota_n(OutputIterator first, Size n, T value)
{
        while (n--)
                *first++ = value++;
        return first;
}

方案2)

template<class OutputIterator, class Size, class T>
OutputIterator iota_n(OutputIterator first, Size n, T value)
{
        return std::generate_n(first, n, [&](){ return value++; });
}    

既能替代品产生相当于code与优化编译器?

Would both alternatives generate equivalent code with optimizing compilers?

更新:结合的非常好的一点@Marc MUTZ来也在其目标点返回的迭代器。这也是如何 的std :: generate_n 得到了更新,在C ++ 11相比,C ++ 98。

UPDATE: incorporated the excellent point of @Marc Mutz to also return the iterator at its destination point. This is also how std::generate_n got updated in C++11 compared to C++98.

推荐答案

作为一个随便举个例子,我编译如下code与 G ++ -S -O2 -masm =英特尔(GCC 4.7.1,x86_32):

As a random example, I compiled the following code with g++ -S -O2 -masm=intel (GCC 4.7.1, x86_32):

void fill_it_up(int n, int * p, int val)
{
    asm volatile("DEBUG1");
    iota_n(p, n, val);
    asm volatile("DEBUG2");
    iota_m(p, n, val);
    asm volatile("DEBUG3");
    for (int i = 0; i != n; ++i) { *p++ = val++; }
    asm volatile("DEBUG4");
}

下面 iota_n 是第一个版本, iota_m 第二。该大会是在这三种情况下这样的:

Here iota_n is the first version and iota_m the second. The assembly is in all three cases this:

    test    edi, edi
    jle .L4
    mov edx, eax
    neg edx
    lea ebx, [esi+edx*4]
    mov edx, eax
    lea ebp, [edi+eax]
    .p2align 4,,7
    .p2align 3
.L9:
    lea ecx, [edx+1]
    cmp ecx, ebp
    mov DWORD PTR [ebx-4+ecx*4], edx
    mov edx, ecx
    jne .L9

使用 -O3 ,三个版本也非常相似,但一个的很多的更长(使用条件的动作和 punpcklqdq 等类)。

With -O3, the three versions are also very similar, but a lot longer (using conditional moves and punpcklqdq and such like).

这篇关于什么将是一个很好的实现iota_n的(缺少的STL算法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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