开一篇文章来“学习”C++

自己的c++学的很烂,开个文章来复习c++,同时也训练下自己的算法基础。

留一行。

首先,复习排序,这里写下 冒泡和快排

 1 //============================================================================
 2 // Name        : sort .cpp
 3 // Author      : 
 4 // Version     :
 5 // Copyright   : Your copyright notice
 6 // Description : Hello World in C++, Ansi-style
 7 //============================================================================
 8 
 9 #include <iostream>
10 using namespace std;
11 
12 //bubble sort
13 //the array[0] is the "smallest" one
14 void bubbleSort(int array[],int n){
15     int p = 1;  //flag
16     int k = n-1,j;   //the array[] end with the array[n-1]
17     int temp;
18     while((k>=1)&&(p==1)){
19         p = 0;
20         for(j = 0;j<k;j++){
21             if(array[j] > array[j+1]){
22                 //swap
23                 temp = array[j];
24                 array[j] = array[j+1];
25                 array[j+1] = temp;
26                 p = 1;
27             }
28         }
29         k--;
30     }
31 }
32 
33 //qsort
34 int comp(const void *a,const void*b){
35     return *(int *)a - *(int *)b;
36 }
37 
38 int main() {
39 
40     int t[10];
41     int m[10];
42     srand(time(0));
43     for(int i = 0;i < 10;i++)
44         t[i] = rand();
45     puts("bubble sort:");
46     for(int i=0;i<10;i++){
47         cout<<t[i]<<" ";
48     }
49     //cout<<endl;
50     puts("");
51     bubbleSort(t,10);
52     for(int i=0;i<10;i++){
53         cout<<t[i]<<" ";
54     }
55     puts("");
56     puts("qsort:");
57 
58     for(int i = 0;i < 10;i++)
59             m[i] = rand();
60     for(int i=0;i<10;i++){
61             cout<<m[i]<<" ";
62     }
63     puts("");
64     qsort(m,10,sizeof(int),comp);
65     for(int i =0;i<10;i++)
66         cout<<m[i]<<" ";
67 
68 
69 
70     return 0;
71 }

2.对指定文本文件按行反序输出到另一个文件

 1 #include<iostream>
 2 #include<fstream>
 3 #include<cstring>
 4 using namespace std;
 5 
 6 //  这个程序来简单的熟悉下c++下的文件操作及理解“流”的概念
 7 //  程序实现了指定目录下文件字符的反转,反转每一行
 8 int main(){
 9     ifstream fin;
10     fin.open("d:\menglei.txt",ios::in);
11     ofstream fout("d:\mengout.txt");//这个很奇葩,它不是两个参数
12     //如果写作ostream fout("d:\mengout.txt",ios::out);
13     //则会报错,说我不是什么标准。。。不过谭浩强c++就是这么写的啊
14 
15     char line[300];
16     int j;
17     while(fin.getline(line,300)){
18         //fin.getline(字符指针,字符个数N,结束符);
19         //功能:一次读取多个字符包括空格,直到读满N-1个,存放到指针指向的数组中
20         for(j = strlen(line)-1;j>=0;--j){
21             //这里的几个+-1什么的很有讲究
22             //否则会出现开头不对齐,会有空格
23             fout<<line[j];
24         }
25         fout<<endl;
26     }
27     return 0;
28 
29 }
转载文章请注明出处: http://www.cnblogs.com/menglei/
原文地址:https://www.cnblogs.com/menglei/p/2864382.html