C++ Bitset 中的 count()函数

首页 / C++入门教程 / C++ Bitset 中的 count()函数

C++ bitset count()函数用于对数字的二进制表示形式中的设置位数进行计数。

count - 语法

int count();

count - 返回值

它以整数值返回设置位数。

count - 例子1

#include <iostream>
#include <bitset>
using namespace std;
int main()
{
bitset<4> b1(string("1100"));
int result=b1.count();
cout<<b1 << " has" <<' ' << result <<" bits";
return 0;
}

输出:

1100 has 2 bits

count - 例子2

#include <iostream>
#include <bitset>
using namespace std;
int main()
{
bitset<4> b1(16);
bitset<4> b2(18);
int result=b1.count();
int result1=b2.count();
cout<<b1 << " has" <<' ' << result <<" set bits" << '\n';
cout<<b2 << " has" <<' ' << result1 <<" set bits";
return 0;
}

输出:

0000 has 0 set bits
0010 has 1 set bits

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

React实战进阶45讲 -〔王沛〕

面试现场 -〔白海飞〕

分布式协议与算法实战 -〔韩健〕

OAuth 2.0实战课 -〔王新栋〕

成为AI产品经理 -〔刘海丰〕

陈天 · Rust 编程第一课 -〔陈天〕

Vue 3 企业级项目实战课 -〔杨文坚〕

结构思考力 · 透过结构看表达 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)