常用函数

	以下是关于<algorithm>头文件下的函数整理:

1.max(x,y)/min(x,y) 最值函数:
必须且只能含有两个参数。求三个数的最大值:

	 d = max(a, max(b, c));

2.abs(x) 绝对值函数:
整 型:abs(x)
浮点型:fabs(x) //math头文件下。

3.swap(x,y) 交换函数:
交换x,y的值。

4.reverse(it1,it2) 反转函数:
将数组指针/容器迭代器在 [it1,it2)之间的元素反转。
注意:
(1)区间是左闭右开的,编程中往往如此。
(2)数组名(arrayName)就是指向第一个元素的指针,arrayName+整数n表示指向n位元素的指针。
(3)对于STL的其他容器,可以使用迭代器,其中仅仅对于vector与string可以用typeName.begin()+n这种迭代器加上整数的写法(类似于数组指针+整数)。

5.next_permutation(start,end) 全排序函数:
(1)start与end可以是数组指针/容器迭代器。
(2)当全排序达到最后一个值时,会返回false,所以该函数可以直接作为判断的语句。
(3)可以利用do…while循环来打印全部排序结果。打印时printf("%d%d…%d",a[0],a[1]…a[n]) 位数要跟全排序结果的位数相同,加粗处排序为连续不断的升序。
(4)next_permutation(index,index+n,cmp) 按照自定义排序方式cmp进行排序,往往用于结构体。

6.fill(index,index+n,x) 区间赋同值函数:
(1)将区间 [index,index+n)全部赋值为x。
(2)该函数可以对任意数据类型使用。

7.sort(start,end,cmp) 排序函数:
(1)默认为升序,比较函数cmp可不填。
(2)序列中的元素要有可比性,如果是字符排序顺序则为字典序。
(3)排序中比较函数cmp的定义:bool cmp(Type Name1,Type Name2){判断语句}
1>主要分三种:基本数据类型数组的排序,结构体的排序(排序题目涉及到多个信息时常用),容器的排序。
2>判断语句的格式:return Name1>Name2 //Name1>Name2时,Name1放在Name2的前面,即降序排列。
3>strcmp(str1,str2):下用来比较两个char型数组的字典序大小。
字典序str1<str2时:strcmp(str1,str2)<0(返回负值)
字典序str1=str2时:strcmp(str1,str2)=0(返回值0)
字典序str1<str2时:strcmp(str1,str2)>0(返回正值)

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct node {
	int x, y;
	friend ostream& operator << (ostream& os, const node& n);
};
ostream& operator << (ostream& os, const node& n)
{
	return os << "(" << n.x << "," << n.y << ")";
}

bool cmp(int a, int b)
{
	return a > b;
}

bool Ncmp(node c, node d)//结构体比较函数
{
	if (c.x != d.x) return c.x > d.x;//一级排序,按照x的大小降序排
	else return c.y < d.y;//x相等时进行二级排序,按照y的大小升序排 
}

bool Scmp(double e, double f)//容器比较函数,形参的类型与容器的类型一致
{
	return e > f;
}

int main()
{
	//基本数据类型(整型)数组cmp排序
	int a[] = {12,9,6,77,54,69,21,101,99,66};
	sort(a, a + 10, cmp);
	for (int i = 0;i < 10;i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;

	//结构体cmp排序
	node ssd[10];
	ssd[0].x = 2; ssd[0].y = 2;
	ssd[1].x = 2; ssd[1].y = 4;
	ssd[2].x = 2; ssd[2].y = 3;
	ssd[3].x = 5; ssd[3].y = 1;
	ssd[4].x = 3; ssd[4].y = 9;
	sort(ssd, ssd + 4, Ncmp);
	for (int i = 0;i < 4;i++)
	{
		cout << ssd[i] << endl ;
	}

	//STL容器cmp排序
	vector<double> v;
	vector<double>::iterator it;
	for (int i = 0;i < 6;i++)
	{
		double t;
		t = i + i * 0.1;
		v.push_back(t);
	}
	sort(v.begin(),v.end(),Scmp);
	for (it =v.begin();it != v.end();it++)
	{
		cout << *it<<" ";
	}

	return 0;
}

8.lower_bound(first,last,val)与upper_bound(first,last,val) 定位函数:
(1)lower_bound(first,last,val)返回第一个大于等于val的位置,upper_bound(first,last,val)返回第一个大于val的位置。
(2)用途范围:有序的数组/容器。
(3)返回:数组指针/容器迭代器。
(4)如果没有寻找到目标元素,则指针/迭代器停留在可插入位置(假设目标元素存在,目标元素的位置。)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值