0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

visual studioのC++20で__builtin_popcountを使う方法

Last updated at Posted at 2024-02-11

visual studioで「__builtin_popcount」を使う方法

「popcount」 を使うとできる

・C++20から使える「popcount」という関数を使うことで全く同じことができる(popcountの方が少しだけ実行時間が早かったです)
・popcountを使う場合は引数の型が「符号無し整数型」でないといけないみたいです。
→int型なら「uint32_t」で、longlong型は「uint64_t」でうまくいきました。

実際にコードにしてみる

pop_countをコードで書くと

C++20
#include <bits/stdc++.h>
using namespace std;
int main(){
  int s = 3;  //2進数で表すと「11」になります
  cout<< popcount(uint32_t(s));
}

出力すると

2

となります。

終わりに

代用する方法を調べていたら見つけました。関数を自作したところ実行時間が__builtin_popcountよりも少し長くて不安でしたが代用できる関数が見つかってよかったです。引用先の記事を投稿してくださった方に感謝します。調べた感じ既出ではなかったので投稿します。引用の許可は取っていません 許してください orz
popcountを教えてくれたリンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?