Best practices for circular shift (rotate) operations in C++

前端 未结 16 1449
情深已故
情深已故 2020-11-22 00:09

Left and right shift operators (<< and >>) are already available in C++. However, I couldn\'t find out how I could perform circular shift or rotate operations.

16条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 00:37

    How abt something like this, using the standard bitset ...

    #include  
    #include  
    
    template  
    inline void 
    rotate(std::bitset& b, unsigned m) 
    { 
       b = b << m | b >> (N-m); 
    } 
    
    int main() 
    { 
       std::bitset<8> b(15); 
       std::cout << b << '\n'; 
       rotate(b, 2); 
       std::cout << b << '\n'; 
    
       return 0;
    }
    

    HTH,

提交回复
热议问题