简体   繁体   中英

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).

The standard library implementation of std::rotate is likely using a call to memmove() for bulk data copying. 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 . That will also compile to memmove() and provide better performance.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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