C++ 函數(shù)

函數(shù)和C type 字符串

簡單統(tǒng)計

#include <iostream>
#include <array>
#include <vector>
using namespace std;
unsigned int c_in_str(const char *str, char ch);
int main()
{
    char mmm[15] = "minimum";
    char * wail = "ululate";
    unsigned int ms = c_in_str(mmm, 'm');
    unsigned int us = c_in_str(wail, 'u');
    cout << "ucount:" << us << endl;
    cout << "count:" << ms << endl;

    return 0;
}

unsigned int c_in_str(const char *str, char ch)
{
    unsigned int count = 0;
    while (*str)
    {
        if (*str == ch)
        {

            count++;
        }
        str++;
    }
    return count;
}

輸入個數(shù)和展示

#include <iostream>
#include <array>
#include <vector>
using namespace std;
unsigned int c_in_str(const char *str, char ch);
char *buildStr(char ch, int n);
int main()
{
    int times;
    char ch;
    cout << "Enter a character:";
    cin >> ch;
    cout << "Enter an integer: ";
    cin >> times;
    char *ps = buildStr(ch, times);
    cout << ps << endl;
    delete [] ps;
    cout << ps << endl;
    ps = buildStr('+', 9);
    cout << ps << endl;
    delete [] ps;
    return 0;
}

char *buildStr(char ch, int n)
{
    char *pstr = new char[n + 1];
    *(pstr + n) = '\0';
    while (n-- > 0)
    {
        pstr[n] = ch;
    }
    return pstr;
}

unsigned int c_in_str(const char *str, char ch)
{
    unsigned int count = 0;
    while (*str)
    {
        if (*str == ch)
        {

            count++;
        }
        str++;
    }
    return count;
}

函數(shù)和string

#include <iostream>
using namespace std;
const int SIZE = 5;
void display(const string * ar,int n);
int main()
{
    string list[SIZE];
    cout << "Enter your " << SIZE << " string. " << endl;
    for (int i = 0; i < SIZE; i++)
    {
        cout << i + 1 << ": ";
        getline(cin, list[i]);
    }

    cout << "your list:\n";
    display(list,SIZE);

    return 0;
}

void display(const string * ar,int n) 
{
    for (int i = 0; i < n; i++)
    {
        cout << i + 1 << ": " + *(ar + i) <<endl;
    }
    
}

函數(shù)和結構體

坐標轉換芥备,傳地址

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;


const int Mins_per_hr = 60;



struct polar
{
    double distance;
    double angle;
};

struct rect
{
    double x;
    double y;
};


void showPolar(const polar* p);
void rect_to_polar(const rect * xypos,polar * pda);
int main()
{
    rect rplace;
    polar pplace;
    cout << "Enter the x and y values: ";
    while (cin >> rplace.x >> rplace.y)
    {
        rect_to_polar(&rplace,&pplace);
        showPolar(&pplace);
    }
}

void showPolar(const polar * p)
{
    const double Rad_to_deg = 57.29577951;
    cout << "polar distance:" << p->distance << ",polar angle:" << p->angle*Rad_to_deg << endl;
}

void rect_to_polar(const rect * xypos,polar * pda)
{
    pda->distance = sqrt(xypos->x) + sqrt(xypos->y);
    pda->angle = atan2(xypos->y, xypos->x);
}

坐標轉換胖替,傳值蚀乔。時間結構計算時間

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
struct travel_time
{
    int hours;
    int mins;
};

travel_time sum(travel_time t1, travel_time t2);
void show_time(travel_time time);
const int Mins_per_hr = 60;



struct polar
{
    double distance;
    double angle;
};

struct rect
{
    double x;
    double y;
};


void showPolar(polar p);
polar rect_to_polar(rect xypos);

int main()
{
    rect rplace;
    polar pplace;
    cout << "Enter the x and y values: ";
    while (cin >> rplace.x >> rplace.y)
    {
        pplace = rect_to_polar(rplace);
        showPolar(pplace);
    }
}

void showPolar(polar p)
{
    const double Rad_to_deg = 57.29577951;
    cout << "polar distance:" << p.distance << ",polar angle:" << p.angle*Rad_to_deg << endl;
}

polar rect_to_polar(rect xypos)
{
    polar answer;
    answer.distance = sqrt(xypos.x) + sqrt(xypos.y);
    answer.angle = atan2(xypos.y, xypos.x);
    return answer;
}

int main2()
{

    travel_time day1 = {5, 45};
    travel_time day2 = {4, 55};
    travel_time trip = sum(day1, day2);

    cout << "2 day total:";

    show_time(trip);
    travel_time day3 = {4, 32};
    show_time(sum(trip, day3));

    return 0;
}

void show_time(travel_time time)
{
    cout << "hours:" << time.hours << ",mins " << time.mins << endl;
}

travel_time sum(travel_time t1, travel_time t2)
{
    travel_time total;

    total.mins = (t1.mins + t2.mins) % 60;
    total.hours = t1.hours + t2.hours + (t1.mins + t2.mins) / 60;

    return total;
}

函數(shù)和數(shù)組

記錄四季消費和總額

#include <iostream>
#include <string>
using namespace std;
const int Seasons = 4;
const array<string, Seasons> Snames = {"Spring", "Summer", "Fall", "Winter"};
void fill(array<double, Seasons> *pa);
void show(array<double, Seasons> ds);
int main()
{
    array<double, Seasons> expenses;
    fill(&expenses);
    show(expenses);
    return 0;
}

void show(array<double, Seasons> ds)
{
    double total = 0.0;
    cout << "\nExpenses\n";
    for (int i = 0; i < Seasons; i++)
    {
        cout << Snames[i] << ": $" << ds[i] << endl;
        total += ds[i];
    }
    cout << "total: $" << total << endl;
}

void fill(array<double, Seasons> *pa)
{
    for (int i = 0; i < Seasons; i++)
    {
        cout << "Enter " << Snames[i] << " expenses: ";
        cin >> (*pa)[i];
    }
}

函數(shù)的遞歸

基本遞歸

#include <iostream>
#include <string>
using namespace std;
void countdown(int n);
int main()
{
    countdown(4);
    return 0;
}

void countdown(int n)
{
    cout << "Countdown......" <<  n << " " << &n << endl;
    if(n > 0) 
    {
        countdown(n - 1);
    }
    cout << n << " kaboom!" << " " << &n << endl;
}

復雜輸出遞歸函數(shù)

#include <iostream>
#include <string>
using namespace std;
const int Len = 66;
const int Divs = 6;
void subdivide(char *ar, int low, int high, int level);
int main()
{
    char ruler[Len];
    for (int i = 1; i < Len - 2; i++)
    {
        ruler[i] = ' ';
    }
    ruler[Len - 1] = '\0';

    int max = Len - 2;
    int min = 0;

    ruler[0] = ruler[max] = '|';
    cout << ruler << endl;

    for (int i = 1; i <= Divs; i++)
    {
        subdivide(ruler, min, max, i);
        cout << ruler << endl;
        for (int j = 0; j < Len - 2; j++)
        {
            ruler[i] = ' ';
        }
    }

    return 0;
}

void subdivide(char *ar, int low, int high, int level)
{
    if (level == 0)
        return;

    int mid = (low + high) / 2;
    ar[mid] = '|';
    subdivide(ar, low, mid, level - 1);
    subdivide(ar, mid, high, level - 1);
}

|                                                               |
|                               |                               |
|               |               |               |               |
|       |       |       |       |       |       |       |       |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

函數(shù)指針

獲取函數(shù)地址
聲明函數(shù)指針
使用函數(shù)指針調(diào)用函數(shù)

#include <iostream>
#include <string>
using namespace std;
double betsy(int lns);
double pam(int lns);
void estimate(int lines, double (*pf)(int));

int main()
{
    int code;
    cout << "How many lines of code do you need? ";
    cin >> code;
    cout << "Here's Betsy's estimate:\n";
    estimate(code, betsy);
     cout << "Here's Pam's estimate:\n";
    estimate(code, pam);
    return 0;
}

void estimate(int lines, double (*pf)(int))
{
    cout << lines << "lines wiil take " << (*pf)(lines) << endl;
}

double betsy(int lns)
{
    return 0.05 * lns;
}

double pam(int lns)
{
    return 0.03 * lns + 0.0004 * lns * lns;
}

默認參數(shù)

#include <iostream>
#include <string>
using namespace std;
const int ArSize = 80;
char *left(const char *str, int n = 1);
int main()
{
    char sample[ArSize];
    cout << "Enter a string: \n";
    cin.get(sample, ArSize);
    char *ps = left(sample, 4);
    cout << ps << endl;
    ps = left(sample);
    cout << ps << endl;
    delete[] ps;
    return 0;
}

char *left(const char *str, int n)
{
    if (n < 0)
        n = 0;
    char *p = new char[n + 1];
    int i;
    for (i = 0; i < n && str[i]; i++)
    {
        p[i] = str[i];
    }
    while (i <= n)
    {
        p[i++] = '\0';
    }
    return p;
}

優(yōu)化1

char *left(const char *str, int n)
{    
    int len = strlen(str);
    if (n < 0)
        len = 0;
    char *p = new char[len + 1];
    int i;
    for (i = 0; i < n && str[i]; i++)
    {
        p[i] = str[i];
    }
    while (i <= len)
    {
        p[i++] = '\0';
    }
    return p;
}

優(yōu)化2

char *left(const char *str, int n)
{
    int m = 0;
    while (m <= n && str[m])
        m++;
    char *p = new char[m + 1];
    int i;
    for (i = 0; i < n && str[i]; i++)
    {
        p[i] = str[i];
    }
    while (i <= m)
    {
        p[i++] = '\0';
    }
    return p;
}

函數(shù)重載記錄數(shù)字個數(shù)

#include <iostream>
#include <string>
using namespace std;
char *left(const char *str, int n = 1);
unsigned long left(unsigned long num, unsigned ct);

int main()
{
    unsigned long n = 12345678;
    const char * trip = "Hawaii!!";
    char * temp;
    int i;
    for (i = 0; i < 10; i++)
    {
        cout << left(n, i) << endl;
        temp = left(trip, i);
        cout << temp << endl;
        delete[] temp;
    }

    return 0;
}



char *left(const char *str, int n)
{
    int m = 0;
    while (m <= n && str[m])
        m++;
    char *p = new char[m + 1];
    int i;
    for (i = 0; i < n && str[i]; i++)
    {
        p[i] = str[i];
    }
    while (i <= m)
    {
        p[i++] = '\0';
    }
    return p;
}

unsigned long left(unsigned long num, unsigned ct)
{
    unsigned digits = 1;
    unsigned long n = num;
    if (ct == 0 || num == 0)
        return 0;

    while (n /= 10)
        digits++;

    if (digits > ct)
    {
        ct = digits - ct;

        while (ct--)
            num /= 10;
        return num;
    }
    else
        return num;
}

引用重載

void staff(double &rs);
void staff(const double &rcs);
void stove(double &r1);
void stove(const double &r2);
void stove(double &&r3);

模板函數(shù)

template <typename T>
void Swap(T &a,T &b)
{
    T temp;
    temp =a;
    a = b;
    b = temp;
}

模版函數(shù)重載

include <iostream>
#include <string>
using namespace std;
const int Limit = 8;


void swapr(int & a, int & b);
void swapr2(int * a, int * b);
void swapr3(int a, int  b);
template <typename T>
void Swap(T &a,T &b)
{
    T temp;
    temp =a;
    a = b;
    b = temp;
}

template <typename T>
void Swap(T *a,T *b,int n)
{
    T temp;
    for (int i = 0; i < n; i++)
    {
        temp = a[i];
        a[i] = b[i];
        b[i] = temp;
    }
    
}


void show(int a[]);

int main()
{
    int wallet1 = 100;
    int wallet2 = 350;
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;
    cout << "using references to swap contents:\n";
    swapr(wallet1,wallet2);
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;

    cout << "using pointers to swap contents:\n";
    swapr2(&wallet1,&wallet2);
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;
    cout << "using value to swap contents:\n";
    swapr3(wallet1,wallet2);
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;

    
    Swap(wallet1,wallet2);
    cout << "wallet1 = "<< wallet1 << " wallet2 = " << wallet2 << endl;

    double i = 20;
    double j = 30;
    Swap(i,j);
        cout << "i = "<< i << " j = " << j << endl;

    int d1[Limit] = {2,3,4,5,1,7,8,9};
    int d2[Limit] = {2,3,2,6,1,8,9,9};
    show(d1);
    show(d2);
    Swap(d1,d2,Limit);
    show(d1);
    show(d2);

    return 0;
}

void swapr(int & a, int & b)
{
    int temp = a;
    a = b;
    b = temp;
}
void swapr2(int * a, int * b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void swapr3(int a, int  b)
{
    int temp = a;
    a = b;
    b = temp;
}


void show(int * a)
{
    cout << a[0] << a[1] << "/";
     cout << a[2] << a[3] << "/";
     for (int i = 4; i < Limit; i++)
     {
        cout << a[i];
     }

     cout << endl;
     

}
  1. 非模版函數(shù)
    void Swap(job &, job &);
  2. 模版函數(shù)
    template <typename T>
    void Swap(T &, T &);
  3. 根據(jù)模版生成的具體化函數(shù)
    template <> void Swap<job>(job &, job &);

如果出現(xiàn)沖突氨淌,編譯器識別優(yōu)先級猎荠,非模版函數(shù) 》 模版生成的具體函數(shù)

隱式實例化:編譯器幫我們生成的代碼。
顯示具體化:程序員斧拍,根據(jù)某個模版要求編譯器生成具體的函數(shù)
template <> void Swap<job>(job &, job &)
{......}
另外一種模版顯示實例化:template void Swap<int>(int, int);

#include <iostream>
#include <string>
using namespace std;

struct debts
{
    char name[50];
    double amount;
};

template <typename T>
void ShowArray(T arr[], int n);

template <typename T>
void ShowArray(T ** arr,int n);

int main()
{
    int things[6] = {13, 31, 103, 301, 310, 130};
    struct debts mr_E[3] =
        {
            {"Ima Wolfe", 2400.0},
            {"Ura Foxe", 1300.0},
            {"David", 1800.0}};
    double *pd[3];
    for (int i = 0; i < 3; i++)
    {
        pd[i] = &mr_E[i].amount;
    }

    "cout << Liting Mr.E's debts:\n";
    ShowArray(things,6);
    ShowArray(pd, 3);

    return 0;
}

template <typename T>
void ShowArray(T * arr, int n)
{
    cout << "templateA\n";
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << ' ';
        cout << endl;
    }
}
template <typename T>
void ShowArray(T ** arr,int n)
{
    cout << "templateB\n";
    for (int i = 0; i < n; i++)
    {
        cout << *arr[i] << ' ';
        cout << endl;
    }

}

根據(jù)模版生成的具體化函數(shù) 編譯的時候會動態(tài)找合適的模版雀扶,如果void ShowArray(T ** arr,int n) 去掉的話,那么肆汹, ShowArray(pd, 3); 打印的將會是地址愚墓。加上這個模版打印的就是具體的數(shù)值了。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
禁止轉載昂勉,如需轉載請通過簡信或評論聯(lián)系作者浪册。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市岗照,隨后出現(xiàn)的幾起案子村象,更是在濱河造成了極大的恐慌,老刑警劉巖攒至,帶你破解...
    沈念sama閱讀 206,013評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件厚者,死亡現(xiàn)場離奇詭異,居然都是意外死亡迫吐,警方通過查閱死者的電腦和手機库菲,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,205評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來志膀,“玉大人熙宇,你說我怎么就攤上這事∥嗳矗” “怎么了奇颠?”我有些...
    開封第一講書人閱讀 152,370評論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長放航。 經(jīng)常有香客問我烈拒,道長,這世上最難降的妖魔是什么广鳍? 我笑而不...
    開封第一講書人閱讀 55,168評論 1 278
  • 正文 為了忘掉前任荆几,我火速辦了婚禮,結果婚禮上赊时,老公的妹妹穿的比我還像新娘吨铸。我一直安慰自己,他們只是感情好祖秒,可當我...
    茶點故事閱讀 64,153評論 5 371
  • 文/花漫 我一把揭開白布诞吱。 她就那樣靜靜地躺著舟奠,像睡著了一般。 火紅的嫁衣襯著肌膚如雪房维。 梳的紋絲不亂的頭發(fā)上沼瘫,一...
    開封第一講書人閱讀 48,954評論 1 283
  • 那天,我揣著相機與錄音咙俩,去河邊找鬼耿戚。 笑死,一個胖子當著我的面吹牛阿趁,可吹牛的內(nèi)容都是我干的膜蛔。 我是一名探鬼主播,決...
    沈念sama閱讀 38,271評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼脖阵,長吁一口氣:“原來是場噩夢啊……” “哼皂股!你這毒婦竟也來了?” 一聲冷哼從身側響起独撇,我...
    開封第一講書人閱讀 36,916評論 0 259
  • 序言:老撾萬榮一對情侶失蹤屑墨,失蹤者是張志新(化名)和其女友劉穎躁锁,沒想到半個月后纷铣,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,382評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡战转,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,877評論 2 323
  • 正文 我和宋清朗相戀三年搜立,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片槐秧。...
    茶點故事閱讀 37,989評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡啄踊,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出刁标,到底是詐尸還是另有隱情颠通,我是刑警寧澤,帶...
    沈念sama閱讀 33,624評論 4 322
  • 正文 年R本政府宣布膀懈,位于F島的核電站顿锰,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏启搂。R本人自食惡果不足惜硼控,卻給世界環(huán)境...
    茶點故事閱讀 39,209評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望胳赌。 院中可真熱鬧牢撼,春花似錦、人聲如沸疑苫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,199評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至撼短,卻和暖如春碰逸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背阔加。 一陣腳步聲響...
    開封第一講書人閱讀 31,418評論 1 260
  • 我被黑心中介騙來泰國打工饵史, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人胜榔。 一個月前我還...
    沈念sama閱讀 45,401評論 2 352
  • 正文 我出身青樓胳喷,卻偏偏與公主長得像,于是被迫代替她去往敵國和親夭织。 傳聞我的和親對象是個殘疾皇子吭露,可洞房花燭夜當晚...
    茶點故事閱讀 42,700評論 2 345

推薦閱讀更多精彩內(nèi)容