简体   繁体   English

为什么 std::rotate 比这种方式更快?

[英]Why is std::rotate faster than this way of doing it?

void rotate(vector <int> &a)
{
    int lastElem = a[a.size()-1];
    
    for(int i=a.size()-1;i>0;i--){
       a[i] = a[i-1];
    }
    
    a[0] = lastElem;
}

Versus相对

rotate(a.begin(),a.end()-1,a.end());

As far as I can see the algorithm above is O(n) so why is STL way faster(I thought it was linear time as well).据我所见,上面的算法是 O(n) 那么为什么 STL 更快(我认为这也是线性时间)。

The standard library implementation of std::rotate is likely using a call to memmove() for bulk data copying. std::rotate的标准库实现很可能使用调用memmove()进行批量数据复制。 That would be one reason that it's faster than your hand-written loop.这将是它比您的手写循环更快的原因之一。

Since you are only rotating a single element you can replace your loop with a call tostd::copy_backward .由于您只旋转单个元素,您可以通过调用std::copy_backward来替换循环。 That will also compile to memmove() and provide better performance.这也将编译为memmove()并提供更好的性能。

void rotate(std::vector<int> &a)
{
    int lastElem = a.back();
    std::copy_backward(a.begin(), a.end() - 1, a.end()); // memmove()
    a.front() = lastElem;
}

You can examine the generated assembly here on Compiler Explorer .您可以在 Compiler Explorer 上检查生成的程序集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM