C++复习之运算符重载,数组排序,vector

最近工作要看C++程序,发现才过了几个月,写起C++程序来,完全陌生了,什么都只记得印象,具体东西都要上网查。比如:运算符重载,现在真是完全不会写了。所以现在赶紧记下来,省的以后又忘记了。

#include "Time.h"

Time operator+ (Time time1,Time time2)

{

time1.addTime(time2);

return time1;

}

Time operator- (Time time1,Time time2)

{

time1.minusTime(time2);

return time1;

}

另:1.在VS2003时写的#include<iostream.h>报错了,换成#include<iostream> using namespace std;这都能忘。。。

2.数组排序

#include "stdafx.h"
//#include "iostream.h"
#include<iostream>
using namespace std;
int cmp(const void *a,const void *b)
{
    return *(int *)b - *(int *)a;
}
int _tmain(int argc, _TCHAR* argv[])
{
    int array[10];
    for(int i=0;i<10;i++)
    {

        array[i] = rand();
    }
    for(int i=0;i<10;i++)
    {

        cout<<array[i]<<endl;
    }
    qsort(array,10,sizeof(array[0]),cmp);
    cout<<"after sort:"<<endl;
    for(int i=0;i<10;i++)
    {

        cout<<array[i]<<endl;
    }
    system("pause");
    return 0;
    
}

3.vector 迭代器这个还是不熟悉啊

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool cmp(int a,int b)
{

    return a>b;
}
int _tmain(int argc, _TCHAR* argv[])
{
    vector <int> vi;
    for(int i=0;i<10;i++)
    {
        int temp = rand();
        vi.push_back(temp);
    }
    for(vector<int>::iterator m=vi.begin();m != vi.end();m++)
    {

        cout<<*m<<endl;
    }
    sort(vi.begin(),vi.end(),cmp);
    cout<<"after sort"<<endl;
    for(vector<int>::iterator m=vi.begin();m != vi.end();m++)
    {

        cout<<*m<<endl;
    }
    system("pause");
    return 0;
}

4.c++文件读写 只是最简单的,在文件中存入两个int数,和读出

#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
 int _tmain(int argc, _TCHAR* argv[])
{
//     fstream f;
//     f.open("d:\\try.txt",ios::in);
//     if(f)
//     int i;
//     double d;
//     char c;
//     char s[20];
// //     f>>i>>d>>c;               //读取数据
 ifstream fin("d:\\task3.txt");
 if(fin)
 {

     //cout<<"aaa"<<endl;
     int m,n;
     char c;
     fin>>m>>c>>n;
     cout<<m<<endl<<n<<endl;
 }
//    if(fin)
//     {
//        char c;
//        while((c=fin.get())!=EOF)
//            cout<<c;
//            
//     }    

 else
 {
    ofstream out("d:\\task3.txt");
    int a = rand();
    int b = rand();
    out<<a;
    out<<"\n";
    out<<b;
    out.close();
 }
 fin.close();
    system("pause");
    return 0;
}