算法学习(1)

1)STL入门

1.sort函数

在algorithm头文件中.使用方法如下:

1、sort函数可以三个参数也可以两个参数,必须的头文件#include < algorithm>和using namespace std; 
2、它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n)

3、Sort函数有三个参数:(第三个参数可不写)

(1)第一个是要排序的数组的起始地址。

(2)第二个是结束的地址(最后一位要排序的地址)

(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序

两个参数:

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[3] = {1,3,2};
	sort(a,a+3);
	for(int i=0;i<3;i++){
		cout << a[i] ;
	}
}

输出结果是升序排列。(两个参数的sort默认升序排序)

三个参数:(先不做考虑,)

函数原型:sort(begin,end,compare)

2.lower_bound函数

lower_bound函数,基本用途是查找有序区间中第一个大于或等于某给定值的元素的位置。

lower_bound(
      ForwardIterator _First, 
      ForwardIterator _Last,
      const Type& _Val
   );
_First 要查找区间的起始位置
_Last 要查找区间的结束位置
_Val 给定用来查找的值

返回值是地址,要想得到数组里值所在的位置,可以减去起始位置

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[3] = {1,3,2};
	sort(a,a+3);
	int p = lower_bound(a,a+3,2) - a;
	if(a[p]==2){
		cout << a[p];
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41709523/article/details/81240178