关于C++一些实用的函数

今天观摩了学霸舍友的博客,突然觉得优秀的人就是做什么都很细心。

她写的博客条理分明,很有逻辑。

反观我的就是贴上代码一键发表。

所以今天以及以后的wjm也要做一个做什么事都超级认真的人~

1.__gcd(x,y)

这个函数是求最大公因数的,以前都是用手写,现在发现居然有这么方便的函数。

这个函数的头文件是#include<algorithm>

//从前手写的gcd函数
int gcd(int x,int y)
{
    if(!y)
       return x;
    else
        return gcd(y,x%y);
}

然后顺便复习一下最小公倍数的求法吧~

int lcm(int a,int b)
{
    return a*b/gcd(a,b);
}

2.reverse(a,a+n)

反转数组,其实在反转向量的时候已经学到了,但是学习就是重复嘛

#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
    int a[9] = {1,2,3,4,5,6,7,8,9};
    reverse(a,a+n);
    for(int i = 0; i < 9; i ++)
	printf("%d ",a[i]);
}
//运行结果:9 8 7 6 5 4 3 2 1 

3.fill(a,a+n,x)

给数组整体赋值函数,其实这类函数还有memset,但是memset是一个字节一个字节赋值的,并且他赋值的数是有限制的。

他只能赋值他的机内码连续8位是相同的数,比如:0x3f3f3f,0,-1;

如果赋值错了数,他不会报错,但是程序会出毛病。

而fill是一个元素一个元素赋值的,所以任何值都可以交给它~

#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
    int a[9] = {1,2,3,4,5,6,7,8,9};
    fill(a,a+9,1);
    for(int i = 0; i < 9; i ++)
	printf("%d ",a[i]);
}
//运行结果:1 1 1 1 1 1 1 1 1 

4.atoi(string)

这个函数可以把字符型数字,就是比如“1221541”->1221541,省去了一步步变得麻烦。

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
        char buffer[25];
	cin>>buffer;
	int res = atoi(buffer);
	printf("%d",res);
}

5.bitset<8>k(n)

这个函数是用来转换二进制的,这个代表的意思就是,将n转化为8位二进制数,并把这个值赋给k

#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<bitset>
using namespace std;
int main()
{
	int n;
	scanf("%d",&n);
	bitset<8>k(n);
	cout<<k;
}
//输入:15  输出:00001111

他的头文件是bitset

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值