STL练习1:主要涉及sort(),lower_bound(),upper_bound(),还有获取数组和字符串长度的方法

#include<bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

//为啥是Int呢 
int cmp(int a,int b){
	return a>b;
}

int main(int argc, char** argv) {
	int num[6]={2,1,7,4,34,15};
	//sort()函数:用于给数组排序,从小到大(默认),第一个参数为数组起始地址,
    //第二个为数组起始地址加上数组长度(即数组最后一个元素的下标+1)
	//若要从大到小排,需引入cmp(),即上面那个的写法sort(a,b,cmp)
	sort(num,num+6);
	//获取数组长度的方法
	int arrlength = sizeof(num)/sizeof(num[0]);
	printf("数组长度为:%d\n",arrlength);
	//获取字符串长度的三种方法
	//str.length(); str.size(); strlen(str);
	cout<<"排好序的数组为:"<<endl; 
	for(int i=0;i<arrlength;i++){
		cout<<num[i]<<endl;
	} 
	//lower_bound(num,num+6,7):用于在一个从小到大排好的数组中找到第一个大于
    //或等于某值的第一个元素,返回该元素的位置(注意不是下标),以此返回值减去数组
    //起始位置,即可得到元素的数组下标
	//upper_bound(num,num+6,7);大致同上,只是找到的是第一个大于某值的第一个元素,没有等于了
	//具体使用如下,通过lower_bound获取第一个num数组中大于等于7的元素的位置,
    //减去数组起始位置(num即可代表)可得到下标position 
	int position1 = lower_bound(num,num+6,7)-num;
	int position2 = upper_bound(num,num+6,7)-num;
	printf("lower返回值:%d\n",lower_bound(num,num+6,7));
	printf("lower_return:%d\nupper_return:%d\n",num[position1],num[position2]);
	//sort从大到小排数组
	sort(num,num+6,cmp); 
	cout<<"从大到小排好序的数组为:"<<endl; 
	for(int i=0;i<arrlength;i++){
		cout<<num[i]<<endl;
	} 
	//在从大到小排好的数组中找元素 ,要加一个greater<type>(),
    //tyoe看情况赋为int或其他 
	int position3=lower_bound(num,num+6,7,greater<int>())-num; 
	int position4=upper_bound(num,num+6,7,greater<int>())-num;
	printf("新lower返回值:%d\n",lower_bound(num,num+6,7,greater<int>()));
	printf("new_lower_return:%d\new_nupper_return:%d\n",num[position3],num[position4]);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值