记录刷题过程中使用到的
STL
函数或容器
1、 c_str()
c_str()
:将字符串转化为字符数组
用法:
string s="abc";
s.c_str();
2、atof
atof
:将字符串转化为浮点数,需要配合c_str()
使用。
用法:
string s="-12.2";
float s1 = atof(s.c_str());
cout<<s1+2;
结果:
3、atoi
atoi
:将字符串转化为整型,需要配合c_str()
使用。
用法:
string s="-12.2";
int k = atoi(s.c_str());
cout<<k;
结果:
4、 priority_queue
默认是大顶堆(从大到小)
priority_queue<int> a;
等同于 priority_queue<int, vector<int>, less<int> > a;
设置为小顶堆(从小到大)
priority_queue<int, vector<int>, greater<int> > c;
5、to_string
to_string()
:将整形或浮点型转化为字符串。
用法:
double f = 12.7;
int x = 12;
string s1 = to_string(x);
cout<<s1<<endl;
string s2 = to_string(f);
cout<<s2;
结果:
6、pair
pair的创建: pair<int,int>p;
pair的赋值: make_pair()
pair的取值: 可以通过p.first和p.second分别访问第一个和第二个元素。
使用:
pair<int,int>p;
p=make_pair(1,2);
cout<<p.first<<" "<<p.second<<endl;
p=make_pair(2,3);
cout<<p.first<<" "<<p.second;
结果:
7、reverse
reverse
:将数组翻转
使用:
int a[]={2,3,4,5,6,7};
reverse(a,a+6);
for(int i=0;i<6;i++)
cout<<a[i]<<" ";
结果:
8、__gcd
__gcd(a,b)
:求两个数的最大公约数
使用:
int a=4,b=6;
int gd = __gcd(a,b);
cout<<gd;
结果:
9、进制转换输出
C++:
读取十进制、八进制、十六进制,输出为十进制、八进制、十六进制
#include<bits/stdc++.h>
using namespace std;
int main(){
int o,d,h;
cin>>oct>>o; //输入八进制数
cin>>hex>>h; //输入十六进制数
cin>>dec>>d; //输入十进制数
cout<<"八进制"<<oct<<o<<"转换为十进制为:";
cout<<dec<<o<<endl;
cout<<"十六进制"<<hex<<h<<"转换为十进制为:";
cout<<dec<<h<<endl;
cout<<"十进制"<<dec<<d<<"转换为十六进制为:";
cout<<hex<<d<<endl;
cout<<"十进制"<<dec<<d<<"转换为八进制为:";
cout<<oct<<d<<endl;
return 0;
}
结果:
补充:(java)
使用Integer.toBinaryString()
将十进制转为二进制字符串
Integer x = 100;
String s = Integer.toBinaryString(x);
System.out.println(s);