常用库函数

常用库函数

memset

memset是计算机中C/C++语言初始化函数。作用是将某一块内存中的内容全部设置为指定的值, 这个函数通常为新申请的内存做初始化工作

每种类型的变量都有各自的初始化方法,memset() 函数可以说是初始化内存的“万能函数”,通常为新申请的内存进行初始化工作。它是直接操作内存空间,mem即“内存”(memory)的意思

==作用:==在一段内存块中填充某个给定的值,它是对较大的结构体或数组进行清零操作的一种最快方法 。

函数原型

void *memset(void *s, int c, unsigned long n);
void *memset(void *s, int ch, size_t n);

//将s中当前位置后面的n个字节 (typedef unsigned int size_t )用 ch 替换并返回 s 

头文件:

#include<string.h>
or
#include<cstringh>

例子

# include <stdio.h>
# include <string.h>
int main(void)
{
    int i;  //循环变量
    char str[10];
    char *p = str;
    memset(str, 0, sizeof(str));  //只能写sizeof(str), 不能写sizeof(p)
    for (i=0; i<10; ++i)
    {
        printf("%d\x20", str[i]);
    }
    printf("\n");
    return 0;
}

根据memset函数的不同,输出结果也不同,
分为以下几种情况:
1、memset(p, 0, sizeof§); //地址的大小都是4字节
0 0 0 0 -52 -52 -52 -52 -52 -52

2、memset(p, 0, sizeof(*p)); //*p表示的是一个字符变量, 只有一字节
0 -52 -52 -52 -52 -52 -52 -52 -52 -52

3、memset(p, 0, sizeof(str));
0 0 0 0 0 0 0 0 0 0

4、memset(str, 0, sizeof(str));
0 0 0 0 0 0 0 0 0 0

5、memset(p, 0, 10); //直接写10也行, 但不专业
0 0 0 0 0 0 0 0 0 0

getline

==功能:==读入一行数据。

c++中有2种getline函数,一种在头文件 中,是istream类的成员函数;另一种是在头文件 中,是普通函数。

在头文件 的getline函数

两种重载形式:

istream& getline (char* s, streamsize n );//读取最多n个字符保存在s对应的数组中,即使大小不够n,
istream& getline (char* s, streamsize n, char delim ); //读取最多n个字符保存在s对应的数组中,遇到delim,或者读完一行,或字数达到限制则终止

tip:

(1)s是一个字符数组,例如char name[100]

(2)n是要读取的字符个数

(3)delim是结束标志,默认为换行符

//istream::getline example
#include <iostream>     // std::cin, std::cout
using namespace std;
int main () {
  char name[256], title[256];
 
  cout << "Please, enter your name: ";
  cin.getline (name,256);
 
  cout << "Please, enter your favourite movie: ";
  cin.getline (title,256);
 
  cout << name << "'s favourite movie is " << title;
 
  return 0;
}
========================================
输出:
Please, enter your name: yyc
Please, enter your favourite movie: car
yyc's favourite movie is car
在头文件中的getline函数

(1)istream& getline (istream& is, string& str, char delim);

istream& getline (istream&& is, string& str, char delim);

(2)istream& getline (istream& is, string& str);

istream& getline (istream&& is, string& str);

tip:

(1)is:表示一个输入流,例如 cin

(2)str:用来存储输入流中的信息

(3)delim:自定义结束字符,默认是 '\n ’

#include<iostream>
#include<string>
int main()
{
	std::string name; //这里定义的是string类型,而不是char
	std::getline(std::cin,name);
	std::cout<<name<<std::endl;
	
	return 0;
} 

getline在while语句中作为判定条件:

  • 不设置终止符
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string name;
	while(getline(cin,name))
	{
		cout<<name<<endl;
	}
	return 0;
} 
  • 使用终止符的while语句(当输入 ’ \n ’ 也不受影响)
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string name;
	while(getline(cin,name,'#'))
	{
		cout<<"输出结果:"<<endl;
		cout<<name<<endl;
	}
	
	
	return 0;
} 

strlen

strlen返回字符数组中有效元素的个数,而不是字符数组的容量

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
	
	
	char c[20]; 
	string s="1234 "; 
	strcpy(c,s.c_str()); 
	
	cout<<strlen(c);
	
	return 0;
} 
========================================
输出:
5

和sizeof()的区别

​ ==strlen(char*)==函数求的是字符串的实际长度,它求得方法是从开始到遇到第一个’\0’,如果你只定义没有给它赋初值,这个结果是不定的,它会从aa首地址一直找下去,直到遇到’\0’停止

char aa[10];cout<<strlen(aa)<<endl; //结果是不定的
char aa[10]={‘\0’}; cout<<strlen(aa)<<endl; //结果为0
char aa[10]=“jun”; cout<<strlen(aa)<<endl; //结果为3
==而sizeof()==返回的是变量声明后所占的内存数,不是实际长度,此外sizeof不是函数,仅仅是一个操作符,strlen是函数。
sizeof(aa) 返回10
int a[10]; sizeof(a) 返回40

min

作用:比较两个值大小然后返回最小值

头文件:

#include <algorithm

例子

#include <algorithm>
 
int a=2;
int b=3;
min(a,b);

max

作用:比较两个值大小然后返回最大值

#include <iostream>//输入输出
#include<algorithm>//max,min

using namespace std;

void main() {
	int a;
	int b;
	cin >> a >> b;
	cout << max(a, b) << ' ';
	cout << min(a, b) << endl;
}

tip:a,b可以是多种数据类型,测试整型,浮点型,double均可。但是两者必须为同一个数据类型

sort

sort()是一个比较灵活的函数,它也会根据我们数据的需要进行排序,对于大部分的排序需求,sort()都是可以满足的。

头文件:

#include<algorithm>

使用方法

​ sort()函数可以对给定区间所有元素进行排序。它有三个参数sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,cmp参数可以不写,如果不写的话,默认从小到大进行排序。如果我们想从大到小排序可以将cmp参数写为greater()就是对int数组进行排序,当然<>中我们也可以写double、long、float等等。如果我们需要按照其他的排序准则,那么就需要我们自己定义一个bool类型的函数来传入。比如我们对一个整型数组进行从大到小排序:

#include<iostream>
#include<algorithm>
using namespace std;

int main(){
	int num[10] = {6,5,9,1,2,8,7,3,4,0};
	sort(num,num+10,greater<int>());
	for(int i=0;i<10;i++){
		cout<<num[i]<<" ";
	}
	
	return 0;
	
} 
========================================
输出:
9 8 7 6 5 4 3 2 1 0

自定义排序准则

使用sort()我们不仅仅可以从大到小排或者从小到大排,还

可以按照一定的准则进行排序。比如说我们按照每个数

的个位进行从大到小排序,我们就可以根据自己的需求来

写一个函数作为排序的准则传入到sort()中

将这个函数定义为:

bool cmp(int x,int y){
	return x % 10 > y % 10;
}

这个cmp函数作为参数传入sort()中即可实现了上述排序需求:

#include<iostream>
#include<algorithm>
using namespace std;

bool cmp(int x,int y){
	return x % 10 > y % 10;
}

int main(){
	int num[10] = {65,59,96,13,21,80,72,33,44,99};
	sort(num,num+10,cmp);
	for(int i=0;i<10;i++){
		cout<<num[i]<<" ";
	}
	
	return 0;
	
} 
========================================
输出:
59 99 96 65 44 13 33 72 21 80

对结构体进行排序

sort()也可以对结构体进行排序,比如我们定义一个结构体

含有学生的姓名和成绩的结构体Student,然后我们按照

每个学生的成绩从高到底进行排序。首先我们将结构体定

义为:

struct Student{
	string name;
	int score;
	Student() {}
	Student(string n,int s):name(n),score(s) {}
};

根据排序要求我们可以将排序准则函数写为:

bool cmp_score(Student x,Student y){
	return x.score > y.score;
}
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

struct Student{
	string name;
	int score;
	Student() {}
	Student(string n,int s):name(n),score(s) {}
};

bool cmp_score(Student x,Student y){
	return x.score > y.score;
}

int main(){
	Student stu[3];
	string n;
	int s;
	for(int i=0;i<3;i++){
		cin>>n>>s;
		stu[i] = Student(n,s);
	}
	
	sort(stu,stu+3,cmp_score);
	
	for(int i=0;i<3;i++){
		cout<<stu[i].name<<" "<<stu[i].score<<endl;
	}
	
	return 0;
}

lower _bound

​ lower_bound()返回一个 iterator 它指向在[first,last)

标记的有序序列中可以插入value,而不会破坏容器顺序

的第一个位置,而这个位置标记了一个不小于value 的值

​ 函数lower_bound()在first和last中的前闭后开区间进

行二分查找,返回大于或等于val的第一个元素位置。如果

所有元素都小于val,则返回last的位置简单来讲就是在一

个区间中进行二分查找,返回第一个大于等于目标值的

元素位置

创建:

lower_bound(start,end,val);

#include<bits/stdc++.h>
using namespace std;
 
int main(){
	int a[14]={1,2,2,3,4,4,4,4,5,6,7,9,9,10};
	cout<<lower_bound(a,a+14,4)<<endl;
	cout<<lower_bound(a,a+14,4)-a<<endl;
    return 0;
}

upper_bound

​ upper_bound也是二分查找函数,定义在

头文件中,用于在区间内查找==第一个大于==

目标值的元素位置

创建:

upper_bound(start,end,val);

#include<bits/stdc++.h>
using namespace std;
 
int main(){
	int a[14]={1,2,2,3,4,4,4,4,5,6,7,9,9,10};
	cout<<upper_bound(a,a+14,4)<<endl;
	cout<<upper_bound(a,a+14,4)-a<<endl;
    return 0;
}

accumulate

作用:

(1)累加求和

(2)自定义类型数据的处理

头文件:

#include<numeric>

累加求和

创建及初始化

int sum = accumulate(vec.begin() , vec.end() , n, 自定义操作函数);

accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值

accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型

可以使用accumulate把string型的vector容器中的元素连接起来:

string sum = accumulate(v.begin() , v.end() , string(" "));

这个函数调用的效果是:从空字符串开始,把vec里的每个元素连接成一个字符串

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int main() {
    vector<string> words{"this ", "is ", "a ", "sentence!"};
    string init, res;
    res = accumulate(words.begin(), words.end(), init);    // 连接字符串
    cout << res << endl;    // this is a sentence!
    return 0;
}

求数组之和

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main() {
    vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int sum = accumulate(arr.begin(), arr.end(), 0); 
    cout << sum << endl;	
    return 0;
}
========================================
输出:
55

求数组之积

需要指定第四个参数,这里使用的是乘法函数 multiplies<type>(), type根据元素的类型选择

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int main() {
    vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int sum = accumulate(arr.begin(), arr.end(), 1, multiplies<int>()); 
    cout << sum << endl;	// 输
    return 0;
}
========================================
输出:
3628800

自定义数据类型的处理

计算数组中每个元素乘以3之后的和
#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int fun(int acc, int num) {
    return acc + num * 3;     // 计算数组中每个元素乘以3
}

int main() {
    vector<int> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int sum = accumulate(arr.begin(), arr.end(), 0, fun);
    cout << sum << endl;	
    return 0;
}
========================================
输出:
165
计算班级内学生的平均分
#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

struct Student {
    string name;
    int score;
    Student() {};   // 无参构造函数
    Student(string name, int score) : name(name), score(score) {};  // 有参构造函数
};

int fun(int acc, Student b) {
    return a + b.score;
}

int main() {
    vector<Student> arr;
    arr.emplace_back("Alice", 82);
    arr.emplace_back("Bob", 91);
    arr.emplace_back("Lucy", 85);
    arr.emplace_back("Anna", 60);
    arr.emplace_back("June", 73);
    int avg_score = accumulate(arr.begin(), arr.end(), 0, fun) / arr.size();	// 总分/学生数
    cout << avg_score << endl;
    return 0;
}

min_element

min_element函数可以返回容器中的最小值的迭代器如果需要调用其值大小前面需要*

头文件:

#include

创建

min_element(first,end,cmp)

max_element

max_element函数可以返回容器中的最大值的迭代器如果需要调用其值大小前面需要*

max_element(first,end,cmp)

其中first和end 分别为选用的容器的范围,而cmp参数是可选参数,我们可以自己设置它的功能

创建

max_element(first,end,cmp)

数组例子

#include<iostream>
#include<algorithm> // 函数头文件
using namespace std;

int main(){
    int a[3] = {3, 1, 2};
    cout << "元素内最大值的位置为: " << max_element(a, a + 3) - a << endl; //输出迭代器要-a,不然输出的是地址
    cout << "元素内最大值的值为: " << * max_element(a, a + 3) << endl;
    cout << "元素内最小值的位置为: " << min_element(a, a + 3) - a << endl;
    cout << "元素内最小值的值为: " << * min_element(a, a + 3) << endl;
}
========================================
输出:
元素内最大值的位置为:0
元素内最大值的值为:3
元素内最小值的位置为:1
元素内最小值的值为:1

字符串例子

#include<iostream>
#include<algorithm> // 函数头文件
using namespace std;

int main(){
    string s = "312";
    cout << "元素内最大值的位置为: " << max_element(s.begin(), s.end()) - s.begin() << endl;
    cout << "元素内最大值的值为: " << * max_element(s.begin(), s.end()) << endl;
    cout << "元素内最小值的位置为: " << min_element(s.begin(), s.end()) - s.begin() << endl;
    cout << "元素内最小值的值为: " << * min_element(s.begin(), s.end()) << endl;
}
========================================
输出:
元素内最大值的位置为:0
元素内最大值的值为:3
元素内最小值的位置为:1
元素内最小值的值为:1

容器例子

#include<iostream>
#include<algorithm> // 函数头文件
#include<vector>
using namespace std;

int main(){
    vector<int> v ={3, 1, 2};
    cout << "元素内最大值的位置为: " << max_element(v.begin(), v.end()) - v.begin() << endl;
    cout << "元素内最大值的值为: " << * max_element(v.begin(), v.end()) << endl;
    cout << "元素内最小值的位置为: " << min_element(v.begin(), v.end()) - v.begin() << endl;
    cout << "元素内最小值的值为: " << * min_element(v.begin(), v.end()) << endl;
}
========================================
输出:
元素内最大值的位置为:0
元素内最大值的值为:3
元素内最小值的位置为:1
元素内最小值的值为:1

自定义排序

#include<iostream>
#include<algorithm> // 函数头文件
using namespace std;
bool cmp(int x, int y){ //反向排序,值越大则权重越小
    return x > y;
}

int main(){
    int a[3] = {3, 1, 2};
    cout << "元素内最大值的位置为: " << max_element(a, a + 3, cmp) - a << endl;
    cout << "元素内最大值的值为: " << * max_element(a, a + 3, cmp) << endl;
    cout << "元素内最小值的位置为: " << min_element(a, a + 3, cmp) - a << endl;
    cout << "元素内最小值的值为: " << * min_element(a, a + 3, cmp) << endl;
}
========================================
输出:
元素内最大值的位置为:1
元素内最大值的值为:1
元素内最小值的位置为:0
元素内最小值的值为:3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值