C++復習の演算子リロード、配列ソート、vector

9996 ワード

最近仕事は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.VS 2003で書いた#includeエラーを報告し、#includeusing 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++ファイルの読み書きは最も簡単で、ファイルに2つの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<<"
"; out<<b; out.close(); } fin.close(); system("pause"); return 0; }