1. 字符串反转,如输入:123abc, 输出:cba321
#include <iostream> #define N 200 using std::cin; using std::cout; using std::endl; void ReverseFun(char *str) { if(str != NULL) { int Len = strlen(str); int i=0,j=Len-1; char temp; while(i<j) { temp = str[i]; str[i++]=str[j]; str[j--]=temp; } } return; } int main(int argc, char *argv[]) { char str[N]; cout<<"Input string:"<<endl; cin.getline(str,N); ReverseFun(str); cout<<"The reverse string:"<<endl; cout<<str<<endl; return 0; }
2. 已知学生信息数据结构
struct stStudentInfo{
char name[256];
int nID;
int nScores;
};
要求按照 nID 升序,全局 nScores降序 实现排序函数。我的理解是,以nScores实现排序,相同分数按照nID进行排序,即主次排序。
#include <iostream> #include <cstring> using std::cin; using std::cout; using std::endl; struct stStudentInfo{ char name[256]; int nID; int nScores; }; void CopyFun(stStudentInfo &dest,stStudentInfo &src) { strcpy_s(dest.name,src.name); dest.nID = src.nID; dest.nScores = src.nScores; } void SortFun(stStudentInfo *stList,int Len) { if(Len>1) { stStudentInfo key; for(int i=1;i<Len;i++) { CopyFun(key,stList[i]); int j = i-1; while(j>=0 && key.nScores >= stList[j].nScores) { if( key.nScores > stList[j].nScores) // 以分数大小排序,主排序排序 { CopyFun(stList[j+1],stList[j]); --j; } else if(key.nID < stList[j].nID) // ID排序为辅,次要排序,结果中ID号为 3,5情况 { CopyFun(stList[j+1],stList[j]); --j; } else if(key.nID == stList[j].nID) // ID相同,出错 { cout<<"nID ERROR!"<<endl; exit(1); } else // ID号已经按序排列,终止while循环,结果中ID号为2,4情况 break; } CopyFun(stList[j+1],key); } } return; } int main(int argc, char *argv[]) { stStudentInfo a[5]; int Len = sizeof(a)/sizeof(struct stStudentInfo); cout<<"Input Students' Info:"<<endl; for(int i=0;i<Len;i++) { cin>>a[i].name>>a[i].nID>>a[i].nScores; } // sort fun SortFun(a,Len); cout<<"OutPut the sorted result:"<<endl; for(int i=0;i<Len;i++) { cout<<a[i].name<<'\t'<<a[i].nID<<'\t'<<a[i].nScores<<endl; } return 0; }