PAT乙级常用函数用法总结

PAT乙级常用函数用法总结,第1张

  1. 所有的题目利用最基本的C语言知识就可以解决,一些要用到结构体,涉及到的数据结构最多到链表,最常用的函数就是strcmp,strcpy,qsort,abs,fabs等
  2. 大数组最好设置为全局,因为main函数在栈空间内,而栈的大小只有几十KB,数组太大会出现栈溢出,因此大数组设置为全局,全局变量占用堆空间,堆空间按需分配,可大可小
  3. 对于错误,末尾的换行不影响格式,
           段错误一般是设置的数组小于题目给定的要求,
           答案错误一般就是代码逻辑有错误,
           运行超时说明题目不能用暴力破解,或者i--写成i++之类的循环体里的错误
  4. 对于测试用例,最好自己带到DEV C++或者其他编译器上面测试一下,一般能发现很多错误,方便改正

1、sort() 排序函数

bool cmp(struct node a,struct node b) {
	if ((a.de + a.cai) != (b.de + b.cai))
		return (a.de + a.cai) > (b.de + b.cai);
	else if (a.de != b.de)
		return a.de > b.de;
	else
		return a.num < b.num;
}
struct node
{
	int num, de, cai;
}v[4];
sort(v[i].begin(), v[i].end(), cmp);

2、substr() 获取子串

string s = "123456";
cout << s.substr(2, 4);
  • 输出结果:2345

3、reverse() 倒置函数

char res[10] = "abcdefghi";
reverse(begin(res), begin(res) + 4);
cout << res;
  • 输出结果:dcbaefghi

4、vector 常用 *** 作

vector  v1(n,1);//初始化一个大小为n,值全为1的数组

v1.push_back(2);//在vector末尾插入元素2
v1.pop_back();//删除vector末尾元素

v1.insert(v1.begin(),3);//在v1第一个位置前插入3
v1.insert(v1.begin()+1,4);//在v1第二个位置前插入4
v1.insert(v1.begin(),5,6);//在v1第一个位置前连续插入5个6

v1.erase(v1.begin());//删除第一个元素
v1.erase(v1.begin()+1);//删除第二个元素
v1.erase(v1.begin(),v1.begin()+3);//删除前三个元素

5、itoa() atoi() stoi()转换

int i = 579;
char s[10];
itoa(i, s, 8); //第三个参数为转换的进制数
cout << s;
  • itoa()输出结果:1103
char s[4] = "107";
int num = atoi(s);
cout << num;
  • atoi()输出结果:107
char s[4] = "107";
int num = stoi(s);
cout << num;
  • stoi()输出结果:107

6、isdigit() & isalpha() & isalnum() 判断字符是否是数字字母

char a = '7', b = 'C';
cout << isdigit(a) << " " << isdigit(b) << "\n"; //判断是否是数字
cout << isalpha(a) << " " << isalpha(b) << "\n"; //判断是否是字母
cout << isalnum(a) << " " << isalnum(b) << "\n"; //判断是否是数字或字母
  • 输出结果:
    4 0
    0 1
    4 1

7、round() 四舍五入

#define CLK_TCK 100
double t1 = 100, t2 = 149, t3 = 150;
cout << round((t2 - t1) / CLK_TCK) << " " << round((t3 - t1) / CLK_TCK);
  • 输出结果:0 1

8、toupper() & tolower() 转换大小写

char a = 'a', b = 'B';
cout << toupper(a) << " " << tolower(b);
  • 输出结果:65 98

9、string::npos 用法

string s = "abcdefg";
int idx = s.find('.');   //作为return value,表示没有匹配项
if (idx == string::npos)
    cout << "This string does not contain any period!" << endl;
idx = s.find('c');
s.replace(idx + 1, string::npos, "x");  string::npos作为长度参数,表示直到字符串结束
cout << s;
  • 输出结果:
    This string does not contain any period!
    abcx

10、upper_bound() & lower_bound() 寻找上界和下界

注意:这里返回的是地址,通过减去数组名获得下标。

upper_bound() 寻找小于指定值的界限(找到第一个大于3的位置),lower_bound() 寻找大于等于指定值的界限(找到第一个大于等于3的位置)

vector nums = { 1, 2, 3, 3, 4, 4, 5 };
int index = upper_bound(nums.begin(), nums.end(), 3) - nums.begin();
cout << index << endl; // >: 4
index = lower_bound(nums.begin(), nums.end(), 3) - nums.begin();
cout << index << endl; // >: 2
  • 输出结果:4 2

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1295410.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存