2012年12月11日火曜日

int型の変数においてbitが立っている数に関して降順にソートする

  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <array>  
  4. #include <bitset>  
  5.   
  6. int main()  
  7. {  
  8.     std::array<int, 10> arr;  
  9.     std::generate(arr.begin(), arr.end(), []{static int index; return index++;});  
  10.   
  11.     std::cout << "before: ";  
  12.     std::for_each(arr.begin(), arr.end(), [](int value){ std::cout << std::bitset<4>(value) << " "; });  
  13.     std::cout << std::endl;  
  14.   
  15.     std::sort(arr.begin(), arr.end(), [](const int &l, const int &r){ return __builtin_popcount(l) > __builtin_popcount(r); });  
  16.   
  17.     std::cout << "after : ";  
  18.     std::for_each(arr.begin(), arr.end(), [](int value){ std::cout << std::bitset<4>(value) << " "; });  
  19.     std::cout << std::endl;  
  20.   
  21.     return 0;  
  22. }  
  23.   
  24. /* Output 
  25. before: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 
  26. after : 0111 0011 0101 0110 1001 0001 0010 0100 1000 0000 
  27. */  
どうでもいいソース.(;´∀`)

0 件のコメント:

コメントを投稿