复习字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//重新复习一下字符串,三种表现形式1.字符串常量;2 存放于数组中,以‘\0'结尾;3.string对象 //主要用char一维数组存放字符串(第二种形式) //用scanf和cin读入字符串时候,会自动添加结尾的\0,,cin和scanf会读入到空格为止, #include<iostream> #include<cstring> using namespace std; int main(){ char x[100]; //读入到空格就停止 // cin>>a;scanf("%s",a); //读入一行字符串 // cin.getline(a,sizeof(a)); // gets(a);//可能会导致数组越界 // cout<<a; //字符串库函数 char a[100]="you",b[100]="love",c[100]="me"; //字符串拷贝 strcpy(a,b); //字符串比较函数,返回0则相等,正数则是str1大于str2 // 是按字典序排序的,排在前面的字符串为小,后面的为大 // int strcmp(char str1[] ,char str2[] ); //求字符串长度函数 // int strlen(char s[]) //字符串拼接函数 strcat(strcat(a,b),c); //字符串转为大写 strupr(char s[]) //字符串转为小写 strlwr(char s[]) cout<<a<<endl<<b<<endl<<c<<endl; } |
stl中的sort和binary_search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//stl-二分查找binary_search 以及sort排序 #include<iostream> #include<algorithm> using namespace std; typedef int elemtype;//要排序的数组的类型 struct rule1{ bool operator()(const elemtype &a1,const elemtype &a2)const{ return a1%10<a2%10;//按个位数从小到大排序 } }; void disp(elemtype a[],int size){ for(int i=0;i<size;i++){ cout<<a[i]<<" "; } cout<<endl; } int main(){ elemtype a[]={12,32,3,44,57,54,97,54,8,6,9}; // cout<<a.length(); sort(a,a+sizeof(a)/sizeof(elemtype),rule1()); disp(a,sizeof(a)/sizeof(elemtype)); //从大到小排序 sort(a,a+sizeof(a)/sizeof(elemtype),greater<elemtype>()); disp(a,sizeof(a)/sizeof(elemtype)); //二分查找的前提是数组已经从小到大排好顺序了,但是数组不一定非得按从小到大的规则,还有很多 //我们自定义的规则。二分查找也有自定义规则 cout<<binary_search(a,a+sizeof(a)/sizeof(elemtype),8,rule1());//如果数组是按rule1排序的,那么就能够找到8 } |